June 2015

Volume 30 Number 6


Xamarin - Implementing and Using Data Binding in Xamarin

By Laurent Bugnion

Data binding is a popular concept in programming these days, especially for client applications. In this article, I’ll discuss what data binding is and how it’s used in technologies that support it natively, such as Windows XAML. After I cover the basic principles of data binding and observable properties, and how these can be used in technologies that don’t support data binding “out of the box,” I’ll show how data binding support can be added to Xamarin.Android and Xamarin.iOS with the MVVM Light Toolkit (mvvmlight.net). This lightweight toolkit is the most popular Model-View-ViewModel (MVVM) framework for platforms such as Windows Presentation Foundation (WPF), Silverlight, Windows Phone, Windows Store, Xamarin.Android, Xamarin.iOS, Xamarin.Forms and more.

I’ll wrap up with a discussion of data binding in Xamarin.Forms, the newest addition to the Xamarin frameworks, which allows you to build the UI in XAML once, and to run it on Android, iOS and Windows Phone.

What Is Data Binding?

Data binding is the process of connecting the UI and the business logic. Through data binding, two connected properties will remain synchronized. This is great because when you change a value on an object (the data model, often called ViewModel), the corresponding property in the UI will also be automatically updated. Similarly, in the case of “two-way” data binding, modifying a value in the UI will automatically update the ViewModel, as well. Data binding has been available for client applications for some time, even before WPF and all the other XAML-based technologies were introduced. For example, in ASP.NET Web Forms, data controls such as the listbox can be data-bound to a collection of items that need to be represented on the screen. In order to “translate” the data item into a visual representation, an item template is typically defined. This is a small snippet of HTML code in which some of the controls show the values contained in the data item’s properties.

In XAML, the concept has been extended and it’s reasonable to say that every XAML developer will use data binding to a greater or lesser extent. While it can be tempting to handle most of the data model changes in source code directly (especially for developers coming from more traditional technologies that don’t support this mechanism), once the power of data binding has been mastered it’s almost impossible to go back to the tedious process of writing the data change management in source code.

More Than Just Data Controls

XAML data binding is for much more than “just” data controls. It allows binding virtually any property of any object to any other property. (Keep in mind that only a special kind of property called a dependency property [DP] can be the target of data binding. DPs don’t exist in Android and iOS, which is why the available data-binding frameworks use some workarounds.)

Data binding is seeing a revived interest in the Web world with the introduction of frameworks such as KnockoutJS and AngularJS, which feature data-binding extensions to the JavaScript code running in the background. These data-binding frameworks are heavily inspired by XAML frameworks and it’s interesting to see a large crowd adopting the principles (such as the MVVM pattern) that have been developed by the XAML communities.

A Declarative Process

Markup technologies like XAML and HTML are called declarative because they allow you to “declare” your intent for the UI. This is typically done at a different point in time than the code implementation, and sometimes even by a different team. For example, in XAML technologies the UI developers responsible for the XAML are called “integrators” or sometimes “interaction developers,” or even the barbaric “devsigner.” This role implies a good understanding of the designer’s vision for the application, and even though integrators are often developers, they sit between two chairs and have a strong creative responsibility in the application development.

Thanks to data binding, it’s possible even on small development teams to strongly differentiate the process of UI creation. When I work on small apps where I’m the sole developer, I like to say I switch hats during the development process. When I work on code such as the data model, data services and so on, I wear my developer hat. When I switch to creating the UI, I then change to my integrator hat.

This separation of roles reflects the separation of concerns that’s often desirable in modern software development. While data binding doesn’t absolutely demand this separation, it’s a very convenient approach that helps you get into the right mindset.

Is There Data Binding in Xamarin?

Just like in Windows Phone, both Xamarin.Android and Xamarin.iOS allow the UI to be built in source code directly, but also offer a more modern approach using an XML file with declarative markup. In Android, this is an AXML file; in iOS a convenient approach is to use the Storyboard files. This is similar to what we do in Windows Phone with XAML. Note that these declarative markup files are not specific to Xamarin; they’re also used in vanilla Android and iOS development.

While convenient (notably because they allow working with a visual designer tool like the ones provided in Xamarin Studio or in Visual Studio), the declarative markup files in Android and iOS are less powerful than XAML. In particular, they lack what XAML calls markup extension. Such expressions are enclosed within curly brackets ({ }). There are a number of these extensions, for example, to access resources located in a XAML document or to create a data binding, as shown in this code snippet:

<Button Content="{Binding ButtonContent}"
        Command="{Binding ExecuteCommand}"
        CommandParameter="{Binding IsChecked, ElementName=LockCheckBox}" />

This markup, which is part of a View, says that a Button control has its Content property bound to a source property called ButtonContent, and its Command property is bound to a source property called ExecuteCommand. Those source properties are found within whatever object is serving as the default data or binding context for the Button’s parents (often the page as a whole), which is typically the ViewModel object. However, you can set the binding context at any level you need. The third line of markup, for example, explic­itly says that the Button CommandParameter is bound to the IsChecked property of another element on the page whose name is LockCheckBox.

Unfortunately, the concept of data binding doesn’t exist natively in Android or iOS so, in the rest of this article, I’ll show you how you can implement data binding for these two platforms in Xamarin, and then how the MVVM Light Toolkit provides an implementation you can use to facilitate the process. Moreover, Xamarin also provides an extension called Xamarin.Forms that uses a XAML markup language similar to Windows for the UI. Xamarin.Forms supports binding declaration in the markup directly, without adding any external framework.

Implementing Data Binding in Android and iOS

I’m going to build a small application that connects to a simple data service and returns a list of flowers, each with a name and description. You’ll find this application, named XamDataBinding, at galasoft.ch/s/xambinding. To keep things simple, I’ll concentrate on one page only, shown in Figure 1. This page, implemented in Android, iOS and Windows Phone, has the following features:

  • A list of flowers. Ideally the list should update itself whenever the underlying data source changes.
  • A button for refreshing the list.
  • Text showing the date and time of the last refresh.
  • A “lock” checkbox or switch. The purpose of this element doesn’t quite make sense in a production scenario but for the demo, imagine that this “locks” the Refresh button when it’s checked.

Sample Application in Android, iOS and Windows Phone
Figure 1 Sample Application in Android, iOS and Windows Phone

The MVVM pattern relies on a few simple principles:

  • Observable objects implement the INotifyPropertyChanged interface. This .NET interface exposes the PropertyChanged event, which should be raised when an observable property is modified.
  • Lists that can change during the course of an application should be stored in ObservableCollection<T> instances.
  • Such a list raises the CollectionChanged event when its content changes (addition, removal or a different sorting order).
  • Some objects expose functionality in a property implementing the ICommand interface. This interface defines an Execute method and a CanExecute method. The latter returns true or false, depending on whether the Execute method can be executed. In addition, ICommand specifies a CanExecute­Changed event. This event must be raised when the value returned by the CanExecute method changes, as this potentially affects the state of bound UI controls.

In the MVVM Light Toolkit, these interfaces are implemented by concrete classes such as the ObservableObject and ViewModelBase (INotifyPropertyChanged), and the RelayCommand (ICommand). In the XamDataBinding example, the Model and ViewModel layers are built with the MVVM Light Toolkit, and stored in a portable class library called XamDataBinding.Data. This library can be shared between Xamarin and Windows.

In MVVM, each View is “driven” by a ViewModel. In Windows and Windows Phone, the ViewModel is typically used as the DataContext, which is a property of the View (Page, Window, UserControl and so forth). This is a convenient way to use data binding without having to always specify the source of the binding. In Android and iOS, there’s no concept of DataContext. Instead, you declare the ViewModel in the View and use it directly. In a small application like the XamDataBinding sample, the ViewModel can be created directly in the View (the Activity in Android, the MainView­Controller in iOS and the MainPage in Windows Phone):

private MainViewModel _vm;
public MainViewModel Vm
{
  get
  {
    return _vm ?? (_vm = new MainViewModel());
  }
}

Implementing Binding and Commanding Without a Framework

To avoid repeating the same thing over and over again, I’ll concentrate here on the Android application of the XamDataBinding sample. However, the exact same concepts apply to the iOS application. Because neither of these platforms supports data binding, I’ll implement binding and commanding manually:

  • I’ll handle the MainViewModel’s PropertyChanged event in the view, checking the name of the property that changed and updating the view accordingly.
  • Some bindings go in two directions (two-way bindings). For example, when a checkbox is clicked, the corresponding Boolean property on the MainViewModel needs to be updated. Without a binding framework, I need to subscribe to the checkbox event and update the ViewModel’s property manually from the View.
  • The Refresh button must execute the RefreshCommand on the MainViewModel. Without a commanding framework, this, too, must be handled manually. I can handle the button’s Click event and call the command’s Execute method from the View directly.
  • Finally, I know that the command can disable the control to which it’s bound. In this case, without a commanding framework, I need to subscribe to the command’s Can­ExecuteChanged event. When this event fires, I can call the command’s CanExecute method and, depending on the returned value, enable or disable the control.

None of these steps is very complex, but the whole process can be tedious and repetitive. In practice, it’s easier to use a binding and commanding framework, such as the one offered by the MVVM Light Toolkit.

Using the MVVM Light Data-Binding Framework

The preceding examples work, but they’re annoying to write because you have to handle the various events and think of all the possible scenarios. They are also more difficult to maintain and to understand, especially when there are many UI elements to handle.

The simple data-binding framework in the MVVM Light Toolkit, in contrast, allows you to create the relationship between the UI elements and the code, as well as the UI elements and commands. Thanks to this binding framework, I can create bindings and attach to commands in the OnCreate method, as shown in Figure 2.

Figure 2 Creating Bindings and Commands

_lastLoadedBinding = this.SetBinding(
  () => Vm.LastLoadedFormatted,
  () => LastLoadedText.Text);
_lockBinding = this.SetBinding(
  () => Vm.IsLocked,
  () => LockCheckBox.Checked,
  BindingMode.TwoWay);
_refreshCommandBinding = this.SetBinding(
  () => LockCheckBox.Checked);
RefreshButton.SetCommand("Click", Vm.RefreshCommand, _refreshCommandBinding);
FlowersList.Adapter = Vm.Flowers.GetAdapter(GetFlowerAdapter);

In Figure 2, first I create a one-way binding between the MainViewModel’s LastLoadedFormatted property and the Text property of TextView. This single line of code takes care of establishing the permanent relationship between these two properties. Note the use of the extension method SetBinding, which is provided by MVVM Light. This method returns the Binding instance that was created. Because the Binding object is written with WeakReferences to avoid memory leaks, this binding should be saved as a private field to prevent the binding from getting automatically detached.

The second statement creates the two-way binding between the IsLocked property of the MainViewModel and the Checked property of the LockCheckBox. Note that, by default, every binding is one-way, so you must specify the TwoWay BindingMode in the SetBinding method.

The third statement creates a special kind of binding, with only a source and no target. The source here is the Checked property of the LockCheckBox. I’ll use this binding in the SetCommand method, to instruct the MainViewModel that the LoadCommand should be reevaluated every time the LockCheckBox’s Checked property changes. In XAML, I’d create a binding on the Button’s CommandParameter. Here, I use a similar construct by creating the binding first, and then passing this instance to the SetCommand method.

The fourth statement sets a command on the RefreshButton. Though I handle the Click event here, I could in fact actuate the command for any event of any UI element. The second parameter of the SetCommand method is the command that must be actuated. Finally, the third parameter is optional and is needed only for commands that require a parameter. As I mentioned, I use the binding I created earlier here.

Setting the List

Finally, there’s a ListView in the UI. MVVM Light offers a very useful extension method called GetAdapter that can be used on any ObservableCollection or any IList. It returns an Android adapter that can be used as the ListView’s Adapter property. Because the MainViewModel’s Flowers property is an ObservableCollection, the UI will automatically be updated whenever the collection changes:

FlowersList.Adapter = Vm.Flowers.GetAdapter(GetFlowerAdapter);

The GetFlowerAdapter method, which is passed to the GetAdapter method, is used to get the row view that will represent one flower. In this example I keep it simple by using a built-in row view that displays the picture and the name of the flower, as Figure 3 shows. It would be very easy, however, to create a custom row view with more details or a different layout.

If I run the application now, I’ll see the UI shown in Figure 1. You can try the following features:

  • Clicking the Lock checkbox disables the Refresh button. The disabling occurs through the RefreshCommand, and its CanExecute method. Check the MainViewModel’s code to see how this is done. Note that the same effect will happen in XAML if you run the included Windows Phone application.
  • When the Refresh button is enabled, clicking it loads the list of flowers asynchronously. Note the code that connects to the Web service is included in the MainViewModel, and is fully reusable on any platform supported by this portable class library.
  • After the list is loaded, the status of TextView is updated with the “last loaded” information. This, too, is done through the binding I created.
  • Running the iOS or the Windows Phone version of the application creates the exact same results. In iOS, the bindings are created in the MainViewController’s ViewDidLoad method. In Windows Phone, I created the bindings in MainPage.xaml.

Figure 3 Creating a Custom ListView Row

private View GetFlowerAdapter(
  int position,
  FlowerViewModel flower,
  View convertView)
{
  if (convertView == null)
  {
    convertView = LayoutInflater.Inflate(
    Android.Resource.Layout.ActivityListItem, null);
  }
  var text = convertView.FindViewById<TextView>(Android.Resource.Id.Text1);
  text.Text = flower.Model.Name;
  var image = convertView.FindViewById<ImageView>(Android.Resource.Id.Icon);
  image.SetImageBitmap(GetImageBitmapFromUrl(flower.ImageUri.AbsoluteUri));
  return convertView;
}

Data Binding in Xamarin.Forms

Last year, Xamarin released the Forms framework, which allows sharing not only code, but also the UI among all supported platforms. This is ideal for building a UI quickly to test code; for example, during the prototyping phase. The Forms framework can also be used for production code, such as line-of-business applications that have to run on multiple platforms.

In contrast to Xamarin.Android and Xamarin.iOS, Xamarin.Forms supports data binding natively. Because it also supports XAML (although a different version than the one available in WPF, Windows Phone and Windows Store), you can write the data binding in the XAML markup directly. This means you can write something like this:

<Label Text="{Binding LastLoadedFormatted}"
       VerticalOptions="Center"
       HorizontalOptions="Center" />

The included sample can be simplified even more by using Xamarin.Forms and reusing the UI on each platform. Of course, for applications where extra care must be taken with the UX, Xamarin.Forms might not be the best solution. But for a whole range of apps, Forms will simplify UI development considerably, freeing you to work on other tasks, such as improving application performance and stability, adding features, and so forth.

Wrapping Up

MVVM Light bindings are different from XAML bindings in that they’re created in code instead of markup. However, many hours were spent making sure that the API is clean. I take this occasion to thank my good friend Corrado Cavalli for his support on the binding implementation and for helping me create a syntax that’s as close as possible to the XAML binding workflow.

Also, for their help, I want to thank the Xamarin crew and especially James Montemagno who reviewed early versions of this binding framework and gave me super valuable advice.

Finally, for more information and a complete code sample, including Windows Phone, Xamarin.Android, Xamarin.iOS and Xamarin.Forms, see my Xamarin Evolve presentation at galasoft.ch/s/evolve14.


Laurent Bugnion is senior director for IdentityMine Inc., a Microsoft partner working with technologies such as WPF, Silverlight, Xbox, Kinect, Windows Store, Windows Phone, Xamarin and UX. He’s based in Zurich, Switzerland. He is also a Microsoft MVP, Microsoft Regional Director and Xamarin MVP.

Thanks to the following technical expert for reviewing this article: Kraig Brockschmidt (Microsoft), Norm Estabrook (Microsoft) and James Montemagno (Xamarin)