Skip to content

MVVM pattern

jorgemht edited this page May 22, 2017 · 3 revisions

Model-View-ViewModel (MVVM) pattern

The purpose of this post is to provide an introduction to the Model-View-ViewModel (MVVM) pattern with Xamarin.It was created in 2005 by Ken Cooper y Ted Peters, two architects of software in Microsoft.

The main players in the MVVM pattern are:

  • The View .... Where the users see our app and interact with it. The responsibility of the view are to define the layout, appearance and behaviour of the screen. The view communicates with the ViewModels through data bindings (data link). The view if depends on 100% of the platform, you can not implement the view Android in iOS ... unless you are using Xamarin.Forms

  • The ViewModel ....  Is an intermediary between view and model, encapsulates the presentation logic of the information in the view. The ViewModel have three responsibility:

    • Notify the view of changes that occur in it and its properties.
    • To control the interactions that happen in the view and to link them to actions in the model as click a button using commands.
    • The one of recovering and "transforming" the information produced in the model and linking it with the view as for date or boolean (yes or no).
  • The Model .... The model abstracts the data source and logic of the application. Here you can observe the access to database, connection with web services or validations associated with logic. Do not forget, our model must be independent of the platform where our application is running (platform agnostic). We must not worry how the data are presented to the user.

mvvm

Example

Currency converter

  1. Pages (View --> MainPage.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" 
            x:Class="CurrencyConverter.Properties.MainPage"
            Padding="12"
            Title="Currency Converter"
            BindingContext="{Binding Main, Source={StaticResource Locator}}">
</ContentPage>
 <StackLayout Padding="8">
        <Label 
            Text="Amount: " /> 
        <Entry
            Text="{Binding Amount, Mode=TwoWay}"
            Keyboard="Numeric"
            Placeholder="Enter an amount ..." />
                       ...
                       ...
                       ...
    </StackLayout>
</ContentPage>
  1. ViewModel( MainViewModel.cs )
public class MainViewModel 
{
     #region Attributes
                       ...
                       ...
                       ...
     #region Properties
                       ...
                       ...
                       ...
     #region Constructors
                       ...
                       ...
                       ...
     #region Commands
                       ...
                       ...
                       ...
     #region Methods
                       ...
                       ...
                       ...
     #region Events
                       ...
                       ...
                       ...
}
  1. Model (ExchangeRates.cs)
public class ExchangeRates
    {
        [JsonProperty("id")]
        public string Disclaimer { get; set; }
        [JsonProperty("license")]
        public string License { get; set; }
        [JsonProperty("timestamp")]
        public int Timestamp { get; set; }
        [JsonProperty("base")]
        public string Base { get; set; }
        [JsonProperty("rates")]
        public Rates Rates { get; set; }
    }

Infrastructure (InstanceLocator.cs)

Services (ApiServices.cs)

    public class ApiServices
    {
        private string appId = "HERE YOUR ID";
	private string url = "/api/latest.json?app_id=";

        public ApiServices()
        {
        }

	public async Task<ExchangeRates> GetAllOrders()
	{
		using (HttpClient client = new HttpClient())
		{
			client.BaseAddress = new Uri("https://openexchangerates.org");
                        var result = await client.GetAsync(this.url+this.appId);

			string data = await result.Content.ReadAsStringAsync();

			if (result.IsSuccessStatusCode)
			{
			         return JsonConvert.DeserializeObject<ExchangeRates>(data);
			}
			else
			{
				return new List<ExchangeRates>();
			}
		}
	}
    }

mvvm

References:

MVVM & Data Binding with Xamarin.Forms

The MVVM Pattern

Model View Viewmodel

Clone this wiki locally