<Window x:Class="CM001_WpfDataBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<StackPanel>
<TextBlock Text="{Binding ElementName=txtInput, Path=Text}" Margin="2.5" />
<TextBox x:Name="txtInput" Margin="2.5"/>
</StackPanel>
<StackPanel >
<TextBlock Text="{Binding ElementName=sldInput, Path=Value}" Margin="2.5"/>
<Slider x:Name="sldInput" Margin="2.5"/>
</StackPanel>
</StackPanel>
</Window>
The object tags we need to focus on are first the <TextBlock> and <TextBox> tags. A TextBlock, as the name implies, is a block of text. In this case, we set the Text property to be bound to the Text property of the txtInput object which is our TextBox. This means that anything we type into out txtInput TextBox will also change the value in the said TextBlock. All these happens because of the magic of Data Binding.So, as another example, we have another
TextBlock object this time with a slider. We again bind the Text property of the TextBlock to the Value property of the sldInput Slider object. Therefore, whenever we move the sldInput's slider to a different position it will prompt a change in the Text property of the TextBlock we are bound to.If compile and run the project you should see a window similar to this:
This example also shows us that we can have anonymous objects in the case of the
StackPanels and the TextBlocks we used.There you have it a very simple introduction to Binding in WPF. Solution files can be downloaded here

No comments:
Post a Comment