Element to element data binding in WPF

Data bindings has existed for quite some time in Windows Forms but in WPF it’s more powerful than ever. In this example I’ll show how to create simple databindings inbetween two WPF elements.

Data bindings are created through the Bindings class. In this very simple example a label is declaratively bound to a slider so the Content of the label always will show the current value of the slider.

<Label Content="{Binding ElementName=slider1, Path=Value}" Name="label1" />
<Slider Name="slider1" Width="100" Height="25" />

Another way of creating this declaratively in XAML is to nest it like this example doing exactly the same thing.

<Label Name="label1">
    <Binding ElementName="slider1" Path="Value" />
<Slider Name="slider1" Width="100" Height="25" />

This type of simple binding can also be made in code.

Binding b = new Binding();
b.ElementName = "slider1";
b.Path = new PropertyPath("Value");

To remove a binding from the code you do it through the BindingOperations class as shown here.

BindingOperations.ClearBinding(label1, ContentProperty);