C# WPF Data Binding


This entry is part 6 of 18 in the series C# WPF

Data binding is the association of two objects, such that one of the objects is always kept up-todate with the value of the other. For example, consider a window that contains two elements—a TextBox at the top and a Slider control beneath it. You’d like to have the TextBox represent the value of the Slider such that when you move the Slider back and forth, the value in the TextBox changes to show the Slider’s current value.

DataBinding1

With data binding, you can just create an association between the TextBox.Text property and the Slider.Value property, and WPF will take care of the updates automatically as they occur. This association is called a binding.

Shown below is the XAML for this program.

<Window x:Class="BindSlider.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:BindSlider" mc:Ignorable="d" Title="Bind Slider" Height="150" Width="360">
    <StackPanel>
        <TextBox Margin="10" Name="tbName">
            <TextBox.Text>
                <Binding ElementName="sldrSlider" Path="Value"></Binding>
            </TextBox.Text>
        </TextBox>
        <!-- Below is a shorter way of writing the same code as the entire TextBox above: 
        <TextBox Margin="10" Text="{Binding ElementName=sldrSlider, Path=Value}"/> --> 
        <Slider Name="sldrSlider" TickPlacement="TopLeft" Margin="10" Maximum="10"/>
        <Label x:Name="label" Content="Book: Illustrated WPF by Daniel M. Solis, Ch 8 page 196" HorizontalAlignment="Left" Height="26" Margin="10,0,0,0" Width="323"/>
    </StackPanel>
</Window>

DataBindingSliderText

Here’s the object if you were to create something similar in the code behind.

Looking at the binding direction.

Next we will look at triggers in another post.

To format the data to two decimal places we use data converters

Series Navigation<< C# WPF Create a Simple Binding Object in Code BehindC# WPF Data Binding and Triggers >>