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"?>

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


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! :)

No comments:

Post a Comment