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 for multiple buttons, I assume that the style is only an instance. What does this mean for binding? I have only one binding (i.e. One binding-object), and button1 and button2 refer to this one binding object? If so, when and how is the binding source determined when buttons 1 and 2 are used as part of various My: Control controls? By this I mean a reference to the source object, and not to the value of the source? Can someone point me to some specifications where this is indicated?

+6
source share
1 answer

I assume the style is only an instance

Yes, here is the proof that using your code

enter image description here

Do I have only one binding (i.e., one binding-object), and button1 and button2 refer to this one binding object?

Yes, since the style contains a snap, and the objects are the same (literally), the snap should be the same.

enter image description here

If so, when and how is the binding source determined when buttons 1 and 2 are used as part of various My: Control controls?

When: When the visual tree is rendered, bindings are evaluated by navigating to the control specified by FindAncestor

How: Now you are talking about implementation details. Although I don’t know exactly how FindAncestor (one way to see through .NET Reflector) works, it probably uses VisualTreeHelper.GetParent(...)

EDIT:

BindingExpression not bound to a Binding object, but you can easily get it like this.

enter image description here

As expected, both buttons have different BindingExpression , but the same Binding objects. BindingExpression binds Target to Source . In this case, the ResolvedSource is null as a result of using the RelativeSource to find the property

enter image description here

+2
source

Source: https://habr.com/ru/post/951892/


All Articles