For a better understanding of WPF bindings:
<Style x:Key="myButton" TargetType="Button">
<Setter
Property="Content"
Value="{Binding
RelativeSource={RelativeSource FindAncestor,AncestorType=My:Control},
Path=Text}">
</Setter>
</Style>
<Button Name="button1" Style="{StaticResource myButton}"></Button>
<Button Name="button2" Style="{StaticResource myButton}"></Button>
When I use this Style on multiple buttons, I assume the Style is only instantiated ones. What does it mean for the Binding? Do I have only one Binding (i.e. one Binding-Object) and button1 and button2 are referencing to this one Binding-object? If so, when and how is the Source of the Binding identified when button1 and button2 are used as part of different My:Control controls? By that I mean reference to the source-object not the value of the source? Can someone point me towards some specification where this is stated?
I assume the Style is only instantiated ones
Yes, here's proof of that using your code
Do I have only one Binding (i.e. one Binding-Object) and button1 and button2 are referencing to this one Binding-object?
Yes, since the style holds the binding and the objects are the same (literally) then the binding has to be the same.
If so, when and how is the Source of the Binding identified when button1 and button2 are used as part of different My:Control controls?
When: When the visual tree is rendered the bindings are evaluated by walking up to the control specified by FindAncestor
How: Now you're talking about implementation details. While I don't know exactly how FindAncestor
works (one way to see is through .NET Reflector), it probably uses VisualTreeHelper.GetParent(...)
EDIT:
the BindingExpression
isn't tied to the Binding
of the object, but you can easily get it like this.
As expected, both buttons have different BindingExpression
but the same Binding
object. The BindingExpression
ties the Target
with the Source
. In this case, ResolvedSource
is null as a result of using RelativeSource
to find the property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With