BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Binding - ItemsSource

The one hundred and second part of the Windows Presentation Foundation Fundamentals tutorial looks further at data binding. This article explains how collections can be bound to items controls.

Updating the Bound List

When you bind the ItemsSource property, you will often want the items to update on screen when they change in the data source. In order to demonstrate how to enable this functionality, we can add the code for the Add button, allowing you to add items to the list at run time. Start by registering the Click event in the button's XAML:

<Button Grid.Column="1" Grid.Row="1" Margin="1" Click="Add_Click">Add</Button>

In the method for the event, we'll take the Text property from the TextBox and add a new string with that value to the ListOfItems collection. Add the method below to the code behind the window.

private void Add_Click(object sender, RoutedEventArgs e)
{
    var dataObject = DataContext as DataObject;
    dataObject.ListOfItems.Add(NewItemInput.Text);
    NewItemInput.Clear();
}

Run the program to see the results. You will find that adding new items doesn't update the visible list. However, if you add a breakpoint on the Add_Click method and step through the code, you will find that the new values are being correctly added to the collection. The problem is that the Window is unaware of the changes.

Observable Collections

In order for a change in a collection to be detected so that the control updates, the data bound property must implement INotifyCollectionChanged. This interface is used in a similar manner to INotifyPropertyChanged. It includes a single event, CollectionChanged, which should be raised to indicate that items have been added or removed.

Rather than implementing your own collections, it is usually easier to use the ObservableCollection<T> class. This subclasses Collection<T>, adding the event and notification code required without further coding.

Let's modify the DataObject class. Firstly, add the following using directive, as the ObservableCollection<T> class is found in the System.Collections.ObjectModel namespace:

using System.Collections.ObjectModel;

Now modify the class to change the type of the collection:

public class DataObject
{
    public DataObject()
    {
        ListOfItems = new ObservableCollection<string>();
        ListOfItems.Add("One");
        ListOfItems.Add("Two");
        ListOfItems.Add("Three");
    }

    public ObservableCollection<string> ListOfItems { get; set; }
}

Run the program again. The Add button will now add new items to the ListBox.

7 October 2014