Article number 9 is here, a bit later on the day since I was home late yesterday from the MVP dinner we had and left at 6am this morning to do the Silverlight Road Show. But here we are with the article of today, December 9th!
Today we are looking at a data binding feature that was introduced with Silverlight 3. The reason I’m dedicating an article to it, is that not that many people seem to know about this little gem, namely element-to-element binding or simply element binding. Regular data binding happens between a source object (for example a Person or a Customer) and a control such as a TextBlock. Element binding happens between 2 controls: a property of element A is bound to a property of element B.
A good example to understand element bindings is the following: a Slider control of which the Value property is bound to the Text property of a TextBlock.
To make the link between the 2 values, we create a binding as usual, but we specify the “source” as being another element, in this case the Slider control using the ElementName property on the binding.
<StackPanel x:Name="SliderStackPanel" Orientation="Horizontal" Grid.Row="0">
<Slider x:Name="YearsToPensionSlider" Width="300" Minimum="0" Maximum="40"
SmallChange="1" LargeChange="1" VerticalAlignment="Center"></Slider>
<TextBlock x:Name="ValueTextBlock"
Text="{Binding ElementName=YearsToPensionSlider, Path=Value}" VerticalAlignment="Center"></TextBlock>
</StackPanel>
We can also make this binding a bi-directional binding. In the image above, in the second row, it’s possible to specify a value manually in the TextBox control. Due to the binding, the slider will also change its value if we specify the binding to be a two way binding, as so:
<StackPanel x:Name="SliderStackPanel2" Orientation="Horizontal" Grid.Row="1">
<Slider x:Name="YearsToPensionSlider2" Width="300" Minimum="0" Maximum="40"
SmallChange="1" LargeChange="1" VerticalAlignment="Center"></Slider>
<TextBox x:Name="ValueTextBox"
Text="{Binding ElementName=YearsToPensionSlider2, Path=Value, Mode=TwoWay}" VerticalAlignment="Center" Width="100"></TextBox>
</StackPanel>
You can download the code for this sample here. This is a Visual Studio 2008 project and works both with Silverlight 3 and Silverlight 4.
SLElementBinding.zip (59.38 KB)