WPF: Data binding

This entry is part 11 of 54 in the series Learn WPF

Data binding is a technique where the applications can present and interact with the data directly.  The data can be data in the database or data you have just input from a text box.

WPF elements such as TextBlock can be bound with data from a variety of sources.

Here in the example below, we demonstrate data binding concept using only XAML.

<Window x:Class="SayHi.MainWindow"
        Title="MainWindow" Height="300" Width="400">
        <TextBlock Text="{Binding Path=Text, ElementName=txtValue}" HorizontalAlignment="Left" Margin="106,50,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="100" Width="215" FontSize="24"/>
        <StackPanel Height="119">
            <Label Content="Enter Something Below:" Height="40" Margin="56,20,150,0"  FontSize="16"/>
            <TextBox Height="22" TextWrapping="Wrap" Name="txtValue" HorizontalAlignment="Left" Margin="100,10,0,60" Width="200"/>


If you type something in the text box, the message will be synchronized with the message you typed and displayed in real time in the MainWindow.

Here, in this example we only have to look at 2 declarations in line 6 and 9.  Line 9 will provide the source and line 6 the target of binding.

In line 9, we have the Name declared as


The Name property of the Textbox is the source property.

In line 6, which is the target, we have

Text="{Binding Path=Text, ElementName=txtValue}"

As we have a property name txtValue for the TextBox, our aim is to access the Text entered in the TextBox.  To access the Text, we have Path=Text in line 6.

So in our target, we have the markup extension identified by {} and we have identified the source using ElementName=txtValue.



Series Navigation<< WPF: Static Resource
WPF: WPF and XAML namespace declarations >>