EditCategory
Data Binding
EditQuestion
Is there a way around the limitation of a binding target always needing a dependency property?
EditAnswer
As a rule, to accept a Binding class instance, a property has to be a Dependency Property. For instance, the following declaration is valid because TextBox.Text is a Dependency Property.
<TextBox Name="textBox1" Text="{Binding Source={...}, Path=...}"/>On the other hand, if we try to bind the X attribute of a Point to the content of this TextBox, the declaration will be invalid because X is not a dependency property.
<Point X="{Binding ElementName=textBox1, Path=Text, Mode=OneWay}"/>However, there is indeed a way to bind this TextBox and this Point.X by declaring the Binding the other way around. To put it simply, if you want to perform a binding between a source property and a target property, you can either declare it on the target property (the usual way) or on the source property (the way we explain in this article).
There are a few things to be aware of first:
1- Since the target property is not a DependencyProperty, the source property has to be one. Otherwise, no binding is possible between the two properties.
2- You have to use the binding mode TwoWay or OneWayToSource. Otherwise, the conceptual target would not be a target! Here's a graph that explains it more clearly.
Classic OneWay binding Inversed OneWay Binding using the same objects
Object A (Source) Object A (Target - binding declared here)
| |
| information flow | information flow
v v
Object B (Target - binding declared here) Object B (Source)
Here, Object B is a Target in declaration Here, Object B is a Target only conceptually.
and conceptually.Here's the example that shows this at work. It shows two TextBox objects providing X and Y values to a Point in Resources. There's also a button that displays the current Point's value in a MessageBox.
<Window x:Class="WindowsApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CLR Property As Binding Target Sample"
Height="300"
Width="300">
<Window.Resources>
<Style x:Key="LabelStyle"
TargetType="{x:Type TextBlock}">
<Setter Property="Margin"
Value="5,3,0,0"/>
</Style>
<Point x:Key="WorkingPoint"/>
</Window.Resources>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="X: "
Style="{StaticResource LabelStyle}"/>
<TextBox Width="50"
Text="{Binding Source={StaticResource WorkingPoint}, Path=X}"/>
<TextBlock Text="Y: "
Style="{StaticResource LabelStyle}"/>
<TextBox Width="50"
Text="{Binding Source={StaticResource WorkingPoint}, Path=Y}"/>
</StackPanel>
<Button Content="Show Value" Click="ShowValue_Clicked"/>
</StackPanel>
</Window>In code behind:
private void ShowValue_Clicked( object sender, RoutedEventArgs e )
{
MessageBox.Show( this.FindResource( "WorkingPoint" ).ToString(), "Point value" );
}
Algebra Homework