Bindings in WPF and C#

WARNING! AVERTISSEMENT! ¡CUIDADO!
This project page is under construction! Last update was December 2013

Contents

back to top

Basics

With bindings you can bind properties from a source (code or WPF) to a target (WPF). The target usually reads a value from the source whenever the source value changes. This read-only binding is called OneWay binding. There are also different directions to bind a value. To define when and how often a target reads the value from the source you can use the UpdateSourceTrigger property. You bind a dependency property of a BindingTarget (the dependency object) to a property of a BindingSource

Binding in general

In this example the slider's value binds to the property Range on the code behind file.

<Window x:Class="Binding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:con="clr-namespace:Binding"
        Title="MainWindow" Height="700" Width="520" KeyDown="Window_KeyDown">
    <Grid Name="maingrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <Slider Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2"
                                    HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Name="slider_range"
                                    Value="{Binding Path=Range, Mode=TwoWay}"
                                    Minimum="-500" Maximum="500" >
        </Slider>
        <DockPanel Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2" Margin="200 0 0 0">
            <Label>Range element binding:</Label>
            <Label Content="{Binding ElementName=slider_range, Path=Value}"></Label>
        </DockPanel>
        <DockPanel Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" Margin="200 0 0 0">
            <Label>Range model binding:</Label>
            <Label Content="{Binding Path=Range, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"></Label>
        </DockPanel>
    </Grid>
</Window>

The Binding source needs to implement the INotifyPropertyChanged interface and needs to have a public event as follows.

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
  PropertyChangedEventHandler handler = PropertyChanged;
  if (handler != null)
  {
    handler(this, new PropertyChangedEventArgs(name));
  }
}

The property then needs to call the OnPropertyChanged method with its own name as a parameter.

private int range = 0;
public int Range {
  get { return this.range; }
  set
  {
    if (this.range != value)
    {
      this.range = value;
      this.OnPropertyChanged("Range");
    }
  }
}

In the above example the first label binds to the slider's value directly. The ElementName selects the desired element, the Path indicates the elements property

<Label Content="{Binding ElementName=slider_range, Path=Value}"></Label>

Binding to an object property

All the other Bindings in the above example occur to an object. The object is set using the DataContext property in the code behind file or when using static objects the DataContext can be set in the XAML directly. The updates occur when the PropertyChanged event is triggered.

Specifying the data source in code behind

this.maingrid.DataContext = this;
back to top

Direction of Bindings

The direction can either be

  • OneWay (default): from source to destination.
  • TwoWay: From source to destination and from destination to source.
  • OneWayToSource: from destination to source (opposite of OneWay). Meaning the destination does not get updated when the source's property value changes.
  • OneTime: causes the source property to initialize the target property, but subsequent changes do not propagate.
back to top

When do updates occur

Bindings that occur from source to destination happens immediately. The property UpdateSourceTrigger changes the behaviour when Bindings include a direction from destination to source.

  • Explicit: Only occurs when the application calls UpdateSource()
  • LostFocus: Source is updated when the target loses focus, e.g. when the TextBox control loses focus
  • PropertyChanged: Binding occurs immediately, e.g. as you type into the TextBox
back to top

Data conversion

back to top

Sample project

Download: Binding examples source code, ZIP

back to top

Further readings

Data Binding (WPF) @MSDN pay special attention to the How-To section

back to top