Overview

DataContext

Establishing the Design-Time data context

Establishing the run-time data context

Binding

<TextBlock Text="{Binding Name}" />

means that the Text attribute of the TextBlock is bound to the Name property of the DataContext object (the ViewModel instance).

Two-way binding

<TextBox Text="{Binding Name, Mode=TwoWay}" />

is similar but now the UI can write to the bound property as well as read from it.

Binding via a Convertor

Some attributes require UI specific values. e.g. the Visibility attribute requires the bound data type to be a Visibility enum which is specific to XAML. We might want to convert our app to HTML and so would prefer a plain boolean on the View-Model. This is solved with Converters. These are classes that live in the Converter.cs file in the View folder that intercept the code between the bound property and the XAML attribute.

In the phone:PhoneApplicationPage.Resources element,

<My_ViewNamespace:BoolToStrings x:Key="BoolToVisibilityConverter"/>

then the actual binding,

<Canvas Visibility="{Binding IsProtected, Convertor=BoolToVisibilityConverter}" />

This passes the value of the IsProtected property through the BoolToVisibilityConverter class before showing in the UI. Converter classes implement the IValueConverter interface like below,

public class BoolToVisibilityConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        if ((bool)value)
        {
            return Visibility.Visible;
        }
        else
        {
            return Visibility.Collapsed;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
       return (Visibility)value == Visibility.Visible;
    }
}

Binding to other XAML elements

INotifyPropertyChanged

Use the following template for you View-Model class to do this,

// ... using declarations here ...

namespace YourAppName.ViewModel {
    public class AppViewModel {
        
        // An example string property
        private string _myString1;
        public string MyString1
        {
            get { return this._myString1; }
            set {
                if (this._myString1 != value)
                {
                    this._myString1 = value;
                    RaisePropertyChanged("MyString");
                }
            }
        }

        // ... Rest of View-Model code here ...

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null) 
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}