WPF: Minimal WPF DataBinding example

WPF (Windows Presentation Foundation) is slated for becoming the next GUI toolkit for Windows (superseding Win32, MFC and Windows Forms). Unlike the others, WPF does not base on Win32 at all, but works on DirectX, providing features like fully vector-based rendering.

WPF has a lot of features, however, in this example we'll look at a particularly nice one: DataBinding. There is an interesting tutorial series from Microsoft about it, but we'll take a real quick and simple look at it here.


The idea behind data bindings is to separate the GUI from the data (I think I heard this before ;) ). In the case of WPF, properties are the ideal interface between GUI and objects. Each time a property is changed, an event will be raised, and the GUI gets notified about it. There is no need to connect it, as this works via reflection, the only code you have to write is the notification that a property has been changed.


In our example, we'll have a small data class like this:

class TestObject : INotifyPropertyChanged
    private string _name;

    public string Name
            return _name;

            if (_name == value) return;

            _name = value;

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));


Pretty simple. The GUI side is equally simple:

<Window x:Class="DataBindingTest.Window1"
    Title="Window1" SizeToContent="WidthAndHeight">
    <StackPanel Height="Auto">
        <Label Name="theLabel" Content="{Binding Name}" />
        <Button Content="Click me" Click="Button_Click" />
        <Button Content="Click me later" Click="Button_Click_1" />

By setting the Content property to {Binding Name}, we tell the GUI to watch the "Name" property of the object we will bind to it. The final step is exactly this, binding some object as the data source.

TestObject t = new TestObject ();
theLabel.DataContext = t; // This is the whole bind operation

That's it! We can now change the property directly, and the GUI will get updated automatically.

void Button_Click(object sender, RoutedEventArgs e)
    t.Name = "foo";


Comments powered by Disqus