Tutorial of the Day 2: Binding Data to Controls on WP7

Data Binding is an indispensable part in creating WP7 Application.

It is important since Mobile application usually rely on data from the Internet. The way to show the data on the screen is the technique of Data Binding.

You may bind an item to the control or a list of items to the controls.

For an item one, you can create a TextBox.

<TextBlock Text="{Binding}" x:Name="myTextbox" />

And in code behind, just add

public class Customer
    public Customer() { }

    public Customer(string name, int age, DateTime dob)
        Age = age;
        Name = name;
        Dob = dob;

    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime Dob { get; set; }

    public override string ToString()
        return Name + " [ " + Age + " ] { " + Dob.ToShortDateString() + " } ";

So now, you can bind the data to the textBox

// Set the data context to a new Recording.
myTextbox.DataContext = new Customer("Steve", 20,
    new DateTime(1990, 11, 18));

But it is not always the case to bind a single data. Data often comes in a bundle.

For example, you have a list of Customer to choose from a Combo Box. Now, our task is to bind data to a Combo Box. So we have to create a Combo Box first, and set the ItemsSource to binding

<ComboBox x:Name="myComboBox" Height="30" Width="200" ItemsSource="{Binding}"/>

And for the set of data, you create a class like the previous one “Customer”. Following by, we need an ObservableCollection to store the list of Customer.

public ObservableCollection<Customer> CustomerList = new ObservableCollection<Customer>();

public Page()

    CustomerList.Add(new Recording("Steve", 20,
        new DateTime(1990,11,18)));
    CustomerList.Add(new Recording("Hazel",
        20, new DateTime(1990, 12, 14)));
    CustomerList.Add(new Recording("Joe",
        20, new DateTime(1990, 3, 5)));

    // Here bind the data to the combo box as DataContext
    myComboBox.DataContext = CustomerList;

After the data is binded, whenever you made changes to the CustomerList, the content inside ComboxBox will changed immediately.

Thanks for reading my tutorial 🙂

Enjoy the brilliant data binding design in Silverlight and Windows Phone 7.

One thought on “Tutorial of the Day 2: Binding Data to Controls on WP7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s