If you are developer who new to Xamarin / Xamarin Forms (like myself), and you have idea for a mobile application you want to develop. You had looked around for several forum or developer’s community to look for where to start. It’s likely you will be encouraged to use MVVM pattern for many of Xamarin application. It is naturally supported by Xamarin.

 

I. What is MVVM ?

It is a design pattern. A way to arrange your project into components that are easier to maintenance.

MVVM separates the concerns between the user interface and the business logic behind it.

Developer can work independently for each component of MVVM.

MVVM pattern

Reference: https://msdn.microsoft.com/en-us/library/hh848246.aspx

Before creating the application, please prepare ideas about user interface & data:

  • How many screens the app should have? What layout & controls should be used?
  • What data our application should processing (image, text, contacts, calendar…) & how we store it.
  • How to make connection between user interface and the data.

For the screens, the main concern is about create pages & views with XAML.

For data, the concern is about the way to group data into class, data type & the storage (local/offline or on cloud/online, data from third-party).

Data and user interface are in separated components, but a control/view is specially design to handle particular type of data.

This is not a completed list of available control/view on Xamarin Forms

Controls Associate Data Type Suitable For
Editor string input multiline text
Entry string input single line text
Label string output text
SearchBar string input text for search
Button string, FileImageSource user input
Image ImageSource graphic content
BoxView Color graphic content
OpenGLView graphic content
ActivityIndicator bool page status
Switch bool status
ProgressBar number statistic
Slider number statistic
Stepper number statistic
DatePicker DateTime year-month-day
TimePicker TimeSpan hour-minute-second
Picker IList group of similar content
ListView IEnumerable group of similar content
TableView group of not similar content
WebView WebViewSource Web URL or HTML content

 

For example, let’s say we want to create a to do list application.

We need an application that help user create a list of tasks that he need to do.

For each item, we need some data such as: task name, description, time, status (done or not).

Matching with above controls, we may think of a way to use our data:

ToDoItem Date Type Control
Name string Entry
Note string Editor
Date DateTime DatePicker
Time TimeSpan TimePicker
Done bool Switch

 

Model: we need a class ToDoItem to group all related data.

Although in C#, DateTime data can contain both Date & Time data, but we have separate control for Date & Time. So, I also separate Date & Time field for ToDoItem.

This is an example, we can use different control for each type of data above. For Done field: the check box maybe more suitable, but we may need a custom control for that.

View: we need a screen to list all the items, a screen to add new item, a screen to view detail of an item. Sketch the layout for the screens in some graphic editor first. After that, we will re-create the layout with XAML.

ViewModel: we handle all data transition & state here. For data storage, I will just use runtime data for demonstration only.

 

II. Setup Xamarin Project with PRISM library

Create Cross Platform App (Xamarin) project. I use Xamarin Forms with PCL Sharing Option.

Install following NuGet packages & their dependencies:

Prism.Core

Prism.Forms

Prism.Unity.Forms

Create 3 folders: Models, Views, ViewModels for the PCL project.

Models: put the code for declare class ToDoItem here.

Views: put the code for screens here, all *.xaml & their code behind files.

ViewModels: put the view model related code here.

 

  • Binding Data

For automatic binding between View & ViewModel, the file name for each component must follow the convention.

View ViewModel
PageName.xaml PageNameViewModel.cs

 

For example: the view name is MainPage.xaml, then the corresponding view model name is MainPageViewModel.cs

For the View, adding following code to *.xaml

xmlns:prism=”clr-namespace:Prism.Mvvm;assembly=Prism.Forms”

prism:ViewModelLocator.AutowireViewModel=”True”

 

For the ViewModel class, it should inherit from BindableBase class.

The project structure should be like this:

PCL

Project structure

ToDoList.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MvvmPrismSample"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="MvvmPrismSample.ToDoList">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="{Binding Greeting}"
                   VerticalOptions="CenterAndExpand"
                   HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

ToDoListViewModel.cs

using Prism.Mvvm;

namespace MvvmPrismSample
{
    public class ToDoListViewModel : BindableBase
    {
        private string greeting;
        public string Greeting
        {
            get { return greeting; }
            set
            {
                SetProperty(ref greeting, value);
            }
        }

        public ToDoListViewModel()
        {
            Greeting = "Welcome to Xamarin.Forms!";
        }
    }
}

When compile & run this project, the screen should display the greeting text properly.

Note that the Greeting text in ViewModel is binding with the Label on the View in .xaml

<Label Text="{Binding Greeting}"

Prism library automatically handling the binding context.

 

  • Binding Command

Assume we have a button on our screen. To handle the pressed event of the button, we can either handle Clicked event on the code behind, or we can use command binding and handle the event in ViewModel instead.

First, create the command on ViewModel:

public DelegateCommand GreetingCommand { get; private set; }

Initialize this command in the constructor:

GreetingCommand = new DelegateCommand(ShowGreeting);

In ShowGreeting() method, we can execute the handling.

Back to the View, binding the command to button is easy:

<Button Command="{Binding GreetingCommand}"

For following sample, each time the button is clicked, the button’s background color is changed.

ToDoList.xaml

<Button Text="Greeting"
        BackgroundColor="{Binding BgColor}"
        Command="{Binding GreetingCommand}"/>

ToDoListViewModel.cs

using Prism.Commands;

private Color _bgColor;
public Color BgColor
{
    get { return _bgColor; }
    set
    {
        SetProperty(ref _bgColor, value);
    }
}
public DelegateCommand GreetingCommand { get; private set; }
public ToDoListViewModel()
{
    BgColor = Color.Default;
    GreetingCommand = new DelegateCommand(ShowGreeting);
}
private void ShowGreeting()
{
    Random rnd = new Random();
    int r = rnd.Next(0, 255);
    int g = rnd.Next(0, 255);
    int b = rnd.Next(0, 255);
    BgColor = Color.FromRgb(r,g,b);
}

Click for animation

Leave a Reply

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>