Thursday, July 24, 2014

Binding to events in Xamarin Forms

When using MVVM, you should at all costs avoid to have a lot of code in the code behind of your View (read Page in Xamarin).

This is a simple sample of how to bind to the click event of a button.

The xaml (of the view)

I created a simple page with a button on it. Note the Command="{Binding Click}". This binds the click event to a property on the ViewModel that has the name Click.

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="MvvmSample.MainPage">

    <Button Command="{Binding Click}" 
            Text="Click me!" 
            VerticalOptions="Center" 
            HorizontalOptions="Center"  />

</ContentPage>

The ViewModel

This is what we bind to, a property called click that returns an object implementing ICommand. 

using System.Diagnostics;
using System.Windows.Input;
using Xamarin.Forms;

namespace MvvmSample.ViewModels
{    
    public class MainPageViewModel
    {
        public ICommand Click
        {
            get {
                return new Command (() => {
                    Debug.WriteLine ("Click");
                });
            }
        }
    }
}

The View (code behind)

This is the file you want to keep as light as possible. Just create the ViewModel and assign it to the BindingContext. You should have some sort of dependency injection to abstract the creation of the ViewModel away. But this is just a simple sample.

using MvvmSample.ViewModels;
using Xamarin.Forms;

namespace MvvmSample
{    
    public partial class MainPage : ContentPage
    {    
        public MainPage ()
        {
            InitializeComponent ();
            BindingContext = new MainPageViewModel ();
        }
    }
}

To sum up

  • Keep the code-behind to a minimum
  • ALWAYS databind your events, don't wire up event handlers in your code behind. This forces all logic to belong the the ViewModel, not the view. Just the way we like it! :)

2 comments:

  1. Some useful information about essay writing services you will find here. So I recommend that you check it out as soon as possible

    ReplyDelete
  2. You are aiming to get a sharp, vibrant and well lit photograph of enough resolution to print at your final output size. Concentrate on making the people look great!
    weddnig confetti

    ReplyDelete