Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styles and Bindings in WPF

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?

like image 708
user1182735 Avatar asked Aug 16 '13 14:08

user1182735


1 Answers

I assume the Style is only instantiated ones

Yes, here's proof of that using your code

enter image description here

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.

enter image description here

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.

enter image description here

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

enter image description here

like image 167
James Sampica Avatar answered Oct 02 '22 16:10

James Sampica