Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

The Simplest Binding Example Ever

0.00/5 (No votes)
5 Sep 2012 1  
This example shows you all three things to learn about binding.

Introduction

All the samples I found on Silverlight binding used collections, or lacked some information, that prevented putting it all together. Here is everything you need to know to get started.

Using the Code

Below, I'll tell you what to do, then show the full code as well.

Step 1: Create an Observable Type

Here, we create a class that implements the INotifyPropertyChanged interface, and raise the appropriate event when one of its properties changes. Start Visual Studio 2010. Create a new Project, and select Silverlight for Windows Phone / Windows Phone Application. Add a new class named ObservableInt. This type will hold an integer value, and will raise a PropertyChanged event whenever its value is changed.

Optional: To make everything clear, remove unused usings (right-click on the code, select Organize Usings, then Remove Unused Usings). Now the code looks like this:

using System;

namespace BindingSample1
{
    public class ObservableInt
    {
    }
}

Let's assume that your class has a property that you want to access via binding. Add such a property:

protected int m_Value;
 
public int Value
{
    get { return m_Value; }
    set
    {
        if (!(this.m_Value.Equals(value)))
        {
            this.m_Value = value;
            NotifyPropertyChanged("Value"); // see in next step
         }
    }
}

Now, implement INotifyPropertyChanged: add a using, an event, and the NotifyPropertyChanged method:

using System;
using System.ComponentModel;
 
namespace BindingSample1
{
    public class ObservablInt : INotifyPropertyChanged
    {
        ...
        public event PropertyChangedEventHandler PropertyChanged;
 
        protected void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

Now the code looks like this:

using System;
using System.ComponentModel;
 
namespace BindingSample1
{
    public class ObservableInt : INotifyPropertyChanged
    {
        protected int m_Value;
 
        public int Value
        {
            get { return m_Value; }
            set
            {
                if (!(this.m_Value.Equals(value)))
                {
                    this.m_Value = value;
                    NotifyPropertyChanged("Value");
                }
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        protected void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Step 2: Set the DataContext of the XAML Page to Your Object

Here, we will create a button whose text will change whenever it is clicked. (The text will show the number of clicks made on the button.)

Open the code-behind file of the Main Page. In Solution Explorer, right click MainPage.xaml and select View Code. Add a member variable of our type:

ObservableInt Counter = new ObservableInt();

Now go to the designer, and add a button to the main page (leave its name "button1").

Double click this button to create its click event handler, and implement it like this:

Counter.Value++;

Set the data context of the page to the Counter we created. Add this to the MainPage constructor:

LayoutRoot.DataContext = Counter;

Remove unused usings.

Now the code (MainPage.xaml.cs) looks like this:

using System.Windows;
using Microsoft.Phone.Controls;
 
namespace BindingSample1
{
    public partial class MainPage : PhoneApplicationPage
    {
        ObservableInt Counter = new ObservableInt();
 
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            LayoutRoot.DataContext = Counter;
        }
 
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Counter.Value++;
        }
    }
}

Step 3: Bind a Control's Property to the Source Property

Now we will bind a target property (button1.Content) to a source property (Counter.Value). In the designer, select the Button you added. On its property sheet, find the Content property, and change its source to binding (click the icon in the line of the Content property, and select Apply Data Binding).

In the XAML editor, change this line...

Button Content="{Binding}"

... to this...

Button Content="{Binding Value}"

Note, that "Value" refers to the Value property of the Counter object (Counter.Value). Why? Because:

  1. Earlier, we set the DataContext of the page to the Counter object, and
  2. The property name specified after Binding refers to one of its properties.

Now you can run the app (in the emulator), click the button, and see its value being incremented. If you want, download the sample solution to see the code.

Then you can go on, and read more complex samples on the web.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here