Xamarin

Xamarin

Xamarin.Forms is an open-source mobile UI framework from Microsoft for building iOS, Android, & Windows apps with .NET from a single shared codebase.
  • Xamarin.Forms is a feature of Xamarin, the popular mobile development framework that extends the .NET developer platform with tools and libraries for building mobile apps.
  • Use Xamarin.Forms built-in pages, layouts, and controls to build and design mobile apps from a single API that is highly extensible. Subclass any control to customize their behavior or define your own controls, layouts, pages, and cells to make your app pixel perfect.

Create a Xamarin App

To start, we will create a Xamarin project. The project type comes with all template files to create Xamarin application before adding anything. Let's open Visual Studio 2019, if you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
On the start window, choose Create a new project.
On the Create a new project window, enter or type xamarin.forms in the search box. Next, choose C# from the Language list. Select the Mobile App (Xamarin.Forms) template, and then choose Next.
In the Configure your new project window, type or enter EFCore5InXamarinApp in the Project name box and click on the Create button.
On the New Mobile App page, select the Flyout option, check the Andriod checkbox, and click on the Create button.
Visual Studio opens your new project and includes the default code files in your project as shown in the Solution Explorer.

Install Entity Framework Core

To use Entity Framework Core we need to install Microsoft.EntityFrameworkCore library. It is available as a nuget package and you can install it using Nuget Package Manager.
In the Package Manager Console window, enter the following command.
1
PM> Install-Package Microsoft.EntityFrameworkCore
Copied!
For SQLite, we need to install Microsoft.EntityFrameworkCore.Sqlite and will get all the packages required for EF Core.
1
PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite
Copied!

Create a Data Model and Database Context

In Solution Explorer, right-click on the Models folder and choose Add > Class. Enter a class file name Author.cs and add the following code.
1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel.DataAnnotations;
4
using System.ComponentModel.DataAnnotations.Schema;
5
using System.Text;
6
​
7
namespace EFCore5InXamarinApp.Models
8
{
9
public class Author
10
{
11
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
12
public string Id { get; set; }
13
public string Name { get; set; }
14
public string Address { get; set; }
15
}
16
}
Copied!
To add a context class, right-click on the Services folder in Solution Explorer, and choose Add > Class. Enter a class file name AuthorContext.cs and add the following code.
1
using EFCore5InXamarinApp.Models;
2
using Microsoft.EntityFrameworkCore;
3
using System;
4
using System.Collections.Generic;
5
using System.Text;
6
​
7
namespace EFCore5InXamarinApp.Services
8
{
9
class AuthorContext : DbContext
10
{
11
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
12
{
13
var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
14
optionsBuilder.UseSqlite(quot;Data Source={path}/AuthorContext.db;");
15
}
16
​
17
public DbSet<Author> Authors { get; set; }
18
}
19
}
Copied!
Add another class to the Services folder and name it AuthorDataStore.cs and add the following code.
1
using EFCore5InXamarinApp.Models;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
​
8
namespace EFCore5InXamarinApp.Services
9
{
10
public class AuthorDataStore : IDataStore<Author>
11
{
12
AuthorContext _context;
13
​
14
public AuthorDataStore()
15
{
16
_context = new AuthorContext();
17
}
18
​
19
public async Task<bool> AddItemAsync(Author author)
20
{
21
_context.Authors.Add(author);
22
_context.SaveChanges();
23
​
24
return await Task.FromResult(true);
25
}
26
​
27
public async Task<bool> UpdateItemAsync(Author author)
28
{
29
var oldAuthor = _context.Authors.Where((Author arg) => arg.Id == author.Id).FirstOrDefault();
30
_context.Authors.Remove(oldAuthor);
31
_context.Authors.Add(author);
32
_context.SaveChanges();
33
​
34
return await Task.FromResult(true);
35
}
36
​
37
public async Task<bool> DeleteItemAsync(string id)
38
{
39
var oldAuthor = _context.Authors.Where((Author arg) => arg.Id == id).FirstOrDefault();
40
_context.Authors.Remove(oldAuthor);
41
_context.SaveChanges();
42
​
43
return await Task.FromResult(true);
44
}
45
​
46
public async Task<Author> GetItemAsync(string id)
47
{
48
return await Task.FromResult(_context.Authors.FirstOrDefault(s => s.Id == id));
49
}
50
​
51
public async Task<IEnumerable<Author>> GetItemsAsync(bool forceRefresh = false)
52
{
53
return await Task.FromResult(_context.Authors);
54
}
55
}
56
}
Copied!
It implements the IDataStore interface and contains all the required database operations. To get the implementation of IDataStore add the following code the BaseViewModel.
1
public IDataStore<Author> AuthDataStore => DependencyService.Get<IDataStore<Author>>();
Copied!

Add Views and ViewModels

Create New Author View and ViewModel

To create a new author view, right-click on the Views folder and select Add > New Item...
Select the Content Page template, enter NewAuthorPage.xaml in the Name field and click on the Add button. Replace the following code in NewAuthorPage.xaml file.
1
<?xml version="1.0" encoding="UTF-8"?>
2
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
3
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4
x:Class="EFCore5InXamarinApp.Views.NewAuthorPage"
5
Shell.PresentationMode="ModalAnimated"
6
Title="New Author"
7
xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
8
ios:Page.UseSafeArea="true">
9
<ContentPage.Content>
10
<StackLayout Spacing="3" Padding="15">
11
<Label Text="Name" FontSize="Medium" />
12
<Entry Text="{Binding Name, Mode=TwoWay}" FontSize="Medium" />
13
<Label Text="Address" FontSize="Medium" />
14
<Editor Text="{Binding Address, Mode=TwoWay}" AutoSize="TextChanges" FontSize="Medium" Margin="0" />
15
<StackLayout Orientation="Horizontal">
16
<Button Text="Cancel" Command="{Binding CancelCommand}" HorizontalOptions="FillAndExpand"></Button>
17
<Button Text="Save" Command="{Binding SaveCommand}" HorizontalOptions="FillAndExpand"></Button>
18
</StackLayout>
19
</StackLayout>
20
</ContentPage.Content>
21
​
22
</ContentPage>
Copied!
Now let's add a view model class for this page by adding a new class in the ViewModels folder, name it NewAuthorViewModel.cs and replace the following code.
1
using EFCore5InXamarinApp.Models;
2
using System;
3
using System.Collections.Generic;
4
using System.Text;
5
using System.Windows.Input;
6
using Xamarin.Forms;
7
​
8
namespace EFCore5InXamarinApp.ViewModels
9
{
10
public class NewAuthorViewModel : BaseViewModel
11
{
12
private string name;
13
private string address;
14
​
15
public NewAuthorViewModel()
16
{
17
SaveCommand = new Command(OnSave, ValidateSave);
18
CancelCommand = new Command(OnCancel);
19
this.PropertyChanged +=
20
(_, __) => SaveCommand.ChangeCanExecute();
21
}
22
​
23
private bool ValidateSave()
24
{
25
return !String.IsNullOrWhiteSpace(name)
26
&& !String.IsNullOrWhiteSpace(address);
27
}
28
​
29
public string Name
30
{
31
get => name;
32
set => SetProperty(ref name, value);
33
}
34
​
35
public string Address
36
{
37
get => address;
38
set => SetProperty(ref address, value);
39
}
40
​
41
public Command SaveCommand { get; }
42
public Command CancelCommand { get; }
43
​
44
private async void OnCancel()
45
{
46
// This will pop the current page off the navigation stack
47
await Shell.Current.GoToAsync("..");
48
}
49
​
50
private async void OnSave()
51
{
52
Author newAuthor = new Author()
53
{
54
Id = Guid.NewGuid().ToString(),
55
Name = Name,
56
Address = Address
57
};
58
​
59
await AuthDataStore.AddItemAsync(newAuthor);
60
​
61
// This will pop the current page off the navigation stack
62
await Shell.Current.GoToAsync("..");
63
}
64
}
65
}
Copied!
Update the NewAuthorPage.xaml.cs to bind the view model with a view.
1
using EFCore5InXamarinApp.Models;
2
using EFCore5InXamarinApp.ViewModels;
3
using System;
4
using System.Collections.Generic;
5
using System.ComponentModel;
6
using Xamarin.Forms;
7
using Xamarin.Forms.Xaml;
8
​
9
namespace EFCore5InXamarinApp.Views
10
{
11
public partial class NewAuthorPage : ContentPage
12
{
13
public Author Author { get; set; }
14
public NewAuthorPage()
15
{
16
InitializeComponent();
17
BindingContext = new NewAuthorViewModel();
18
}
19
}
20
}
Copied!

Create Author Detail View and ViewModel

To create an author detail view, right-click on the Views folder and select Add > New Item...
Select the Content Page template, enter AuthorDetailPage.xaml in the Name field and click on the Add button. Replace the following code in AuthorDetailPage.xaml file.
1
<?xml version="1.0" encoding="utf-8" ?>
2
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
3
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4
x:Class="EFCore5InXamarinApp.Views.AuthorDetailPage"
5
Title="{Binding Title}">
6
​
7
<StackLayout Spacing="20" Padding="15">
8
<Label Text="Name:" FontSize="Medium" />
9
<Label Text="{Binding Name}" FontSize="Small"/>
10
<Label Text="Address:" FontSize="Medium" />
11
<Label Text="{Binding Address}" FontSize="Small"/>
12
</StackLayout>
13
​
14
</ContentPage>
Copied!
Now let's add a view model class for this page by adding a new class in the ViewModels folder, name it AuthorDetailViewModel.cs and replace the following code.
1
using EFCore5InXamarinApp.Models;
2
using EFCore5InXamarinApp.Services;
3
using System;
4
using System.Diagnostics;
5
using System.Threading.Tasks;
6
using Xamarin.Forms;
7
​
8
namespace EFCore5InXamarinApp.ViewModels
9
{
10
[QueryProperty(nameof(AuthorId), nameof(AuthorId))]
11
public class AuthorDetailViewModel : BaseViewModel
12
{
13
private string authorId;
14
private string name;
15
private string address;
16
public string Id { get; set; }
17
​
18
public string Name
19
{
20
get => name;
21
set => SetProperty(ref name, value);
22
}
23
​
24
public string Address
25
{
26
get => address;
27
set => SetProperty(ref address, value);
28
}
29
​
30
public string AuthorId
31
{
32
get
33
{
34
return authorId;
35
}
36
set
37
{
38
authorId = value;
39
LoadAuthorId(value);
40
}
41
}
42
​
43
public async void LoadAuthorId(string authorId)
44
{
45
try
46
{
47
var author = await AuthDataStore.GetItemAsync(authorId);
48
Id = author.Id;
49
Name = author.Name;
50
Address = author.Address;
51
}
52
catch (Exception)
53
{
54
Debug.WriteLine("Failed to Load Author");
55
}
56
}
57
}
58
}
Copied!
Update the AuthorDetailPage.xaml.cs to bind the view model with a view.
1
using EFCore5InXamarinApp.ViewModels;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
​
8
using Xamarin.Forms;
9
using Xamarin.Forms.Xaml;
10
​
11
namespace EFCore5InXamarinApp.Views
12
{
13
[XamlCompilation(XamlCompilationOptions.Compile)]
14
public partial class AuthorDetailPage : ContentPage
15
{
16
public AuthorDetailPage()
17
{
18
InitializeComponent();
19
BindingContext = new AuthorDetailViewModel();
20
}
21
}
22
}
Copied!

Create Authors View and ViewModel

To display all the authors from the database, right-click on the Views folder and select Add > New Item...
Select the Content Page template, enter AuthorsPage.xaml in the Name field and click on the Add button. Replace the following code in AuthorsPage.xaml file.
1
<?xml version="1.0" encoding="utf-8" ?>
2
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
3
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
4
x:Class="EFCore5InXamarinApp.Views.AuthorsPage"
5
Title="{Binding Title}"
6
xmlns:local="clr-namespace:EFCore5InXamarinApp.ViewModels"
7
xmlns:model="clr-namespace:EFCore5InXamarinApp.Models"
8
x:Name="BrowseItemsPage">
9
​
10
<ContentPage.ToolbarItems>
11
<ToolbarItem Text="Add" Command="{Binding AddAuthorCommand}" />
12
</ContentPage.ToolbarItems>
13
<!--
14
x:DataType enables compiled bindings for better performance and compile time validation of binding expressions.
15
https://docs.microsoft.com/xamarin/xamarin-forms/app-fundamentals/data-binding/compiled-bindings
16
-->
17
<RefreshView x:DataType="local:AuthorsViewModel" Command="{Binding LoadAuthorsCommand}" IsRefreshing="{Binding IsBusy, Mode=TwoWay}">
18
<CollectionView x:Name="AuthorsListView"
19
ItemsSource="{Binding Authors}"
20
SelectionMode="None">
21
<CollectionView.ItemTemplate>
22
<DataTemplate>
23
<StackLayout Padding="10" x:DataType="model:Author">
24
<Label Text="{Binding Name}"
25
LineBreakMode="NoWrap"
26
Style="{DynamicResource ListAuthorTextStyle}"
27
FontSize="16" />
28
<Label Text="{Binding Address}"
29
LineBreakMode="NoWrap"
30
Style="{DynamicResource ListAuthorDetailTextStyle}"
31
FontSize="13" />
32
<StackLayout.GestureRecognizers>
33
<TapGestureRecognizer
34
NumberOfTapsRequired="1"
35
Command="{Binding Source={RelativeSource AncestorType={x:Type local:AuthorsViewModel}}, Path=AuthorTapped}"
36
CommandParameter="{Binding .}">
37
</TapGestureRecognizer>
38
</StackLayout.GestureRecognizers>
39
</StackLayout>
40
</DataTemplate>
41
</CollectionView.ItemTemplate>
42
</CollectionView>
43
</RefreshView>
44
</ContentPage>
Copied!
Now let's add a view model class for this page by adding a new class in the ViewModels folder, name it AuthorsViewModel.cs and replace the following code.
1
using EFCore5InXamarinApp.Models;
2
using EFCore5InXamarinApp.Views;
3
using System;
4
using System.Collections.Generic;
5
using System.Collections.ObjectModel;
6
using System.Diagnostics;
7
using System.Text;
8
using System.Threading.Tasks;
9
using Xamarin.Forms;
10
​
11
namespace EFCore5InXamarinApp.ViewModels
12
{
13
public class AuthorsViewModel : BaseViewModel
14
{
15
private Author _selectedAuthor;
16
​
17
public ObservableCollection<Author> Authors { get; }
18
public Command LoadAuthorsCommand { get; }
19
public Command AddAuthorCommand { get; }
20
public Command<Author> AuthorTapped { get; }
21
​
22
public AuthorsViewModel()
23
{
24
Title = "Authors";
25
Authors = new ObservableCollection<Author>();
26
LoadAuthorsCommand = new Command(async () => await ExecuteLoadAuthorCommand());
27
​
28
AuthorTapped = new Command<Author>(OnAuthorSelected);
29
​
30
AddAuthorCommand = new Command(OnAddAuthor);
31
}
32
​
33
async Task ExecuteLoadAuthorCommand()
34
{
35
IsBusy = true;
36
​
37
try
38
{
39
Authors.Clear();
40
var authors = await AuthDataStore.GetItemsAsync(true);
41
foreach (var author in authors)
42
{
43
Authors.Add(author);
44
}
45
}
46
catch (Exception ex)
47
{
48
Debug.WriteLine(ex);
49
}
50
finally
51
{
52
IsBusy = false;
53
}
54
}
55
​
56
public void OnAppearing()
57
{
58
IsBusy = true;
59
SelectedAuthor = null;
60
}
61
​
62
public Author SelectedAuthor
63
{
64
get => _selectedAuthor;
65
set
66
{
67
SetProperty(ref _selectedAuthor, value);
68
OnAuthorSelected(value);
69
}
70
}
71
​
72
private async void OnAddAuthor(object obj)
73
{
74
await Shell.Current.GoToAsync(nameof(NewAuthorPage));
75
}
76
​
77
async void OnAuthorSelected(Author author)
78
{
79
if (author == null)
80
return;
81
​
82
// This will push the AuthorDetailPage onto the navigation stack
83
await Shell.Current.GoToAsync(quot;{nameof(AuthorDetailPage)}?{nameof(AuthorDetailViewModel.AuthorId)}={author.Id}");
84
}
85
}
86
}
Copied!
Update the AuthorsPage.xaml.cs to bind the view model with a view.
1
using EFCore5InXamarinApp.ViewModels;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
​
8
using Xamarin.Forms;
9
using Xamarin.Forms.Xaml;
10
​
11
namespace EFCore5InXamarinApp.Views
12
{
13
[XamlCompilation(XamlCompilationOptions.Compile)]
14
public partial class AuthorsPage : ContentPage
15
{
16
AuthorsViewModel _viewModel;
17
public AuthorsPage()
18
{
19
InitializeComponent();
20
BindingContext = _viewModel = new AuthorsViewModel();
21
}
22
​
23
protected override void OnAppearing()
24
{
25
base.OnAppearing();
26
_viewModel.OnAppearing();
27
}
28
}
29
}
Copied!
Let's update the App.xaml.cs to create and initialize the database with test data.
1
using EFCore5InXamarinApp.Models;
2
using EFCore5InXamarinApp.Services;
3
using EFCore5InXamarinApp.Views;
4
using System;
5
using System.Linq;
6
using Xamarin.Forms;
7
using Xamarin.Forms.Xaml;
8
​
9
namespace EFCore5InXamarinApp
10
{
11
public partial class App : Application
12
{
13
​
14
public App()
15
{
16
InitializeComponent();
17
​
18
using (var context = new AuthorContext())
19
{
20
context.Database.EnsureDeleted();
21
context.Database.EnsureCreated();
22
​
23
context.Authors.Add(new Author() { Name = "Karl Jablonski", Address = "Skagen 21, Stavanger, Norway" });
24
context.Authors.Add(new Author() { Name = "Matti Karttunen", Address = "Keskuskatu 45, Helsinki, Finland" });
25
context.Authors.Add(new Author() { Name = "Tom Erichsen", Address = "305 - 14th Ave. S. Suite 3B, Seattle, USA" });
26
​
27
context.SaveChanges();
28
​
29
var list = context.Authors.ToList();
30
}
31
​
32
DependencyService.Register<AuthorDataStore>();
33
MainPage = new AppShell();
34
}
35
​
36
protected override void OnStart()
37
{
38
}
39
​
40
protected override void OnSleep()
41
{
42
}
43
​
44
protected override void OnResume()
45
{
46
}
47
}
48
}
Copied!
To register the route for the author pages, replace the following code in AppShell.xaml.cs
1
using EFCore5InXamarinApp.ViewModels;
2
using EFCore5InXamarinApp.Views;
3
using System;
4
using System.Collections.Generic;
5
using Xamarin.Forms;
6
​
7
namespace EFCore5InXamarinApp
8
{
9
public partial class AppShell : Xamarin.Forms.Shell
10
{
11
public AppShell()
12
{
13
InitializeComponent();
14
Routing.RegisterRoute(nameof(AuthorDetailPage), typeof(AuthorDetailPage));
15
Routing.RegisterRoute(nameof(NewAuthorPage), typeof(NewAuthorPage));
16
}
17
​
18
private async void OnMenuItemClicked(object sender, EventArgs e)
19
{
20
await Shell.Current.GoToAsync("//LoginPage");
21
}
22
}
23
}
Copied!
Now we also need to add the options to the menu in AppShell.xaml file to navigate to the Authors page.
1
<FlyoutItem Title="Authors" Icon="icon_feed.png">
2
<ShellContent Route="AuthorsPage" ContentTemplate="{DataTemplate local:AuthorsPage}" />
3
</FlyoutItem>
Copied!
Let's run your application and click on the Authors menu option.
To add a new author tap the ADD button which is on the top right corner, it will navigate to the New Author Page.
Enter Name and Address and click on the SAVE button and you will see a new author is added.
To view the detail, tap on an author and it will navigate to the detail page.
Last modified 4mo ago