Click here to Skip to main content
15,888,521 members
Articles / Programming Languages / C#

The Simplest Binding Example Ever

Rate me:
Please Sign up or sign in to vote.
3.00/5 (5 votes)
5 Sep 2012CPOL2 min read 18.7K   113   9   5
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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:

C#
Counter.Value++;

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

C#
LayoutRoot.DataContext = Counter;

Remove unused usings.

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

C#
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...

C#
Button Content="{Binding}"

... to this...

XML
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Hungary Hungary
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionnot bad Pin
BillW336-Sep-12 4:34
professionalBillW336-Sep-12 4:34 
GeneralMy vote of 2 Pin
SledgeHammer015-Sep-12 13:03
SledgeHammer015-Sep-12 13:03 
GeneralMy vote of 5 Pin
VuduDog5-Sep-12 2:48
VuduDog5-Sep-12 2:48 
GeneralMy vote of 1 Pin
Thornik5-Sep-12 0:05
Thornik5-Sep-12 0:05 
QuestionI fixed the formatting. Pin
Pete O'Hanlon4-Sep-12 3:29
mvePete O'Hanlon4-Sep-12 3:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.