Associate WPF with PlacementTarget and RelativeSource

Can you explain the following WPF code:

DataContext="{Binding Path=PlacementTarget,RelativeSource={x:Static RelativeSource.Self}}"> 

I find it very confusing. What is the purpose of placement and what is the relative source?

+4
source share
3 answers

It looks like a hack that is used for popup elements such as ContextMenus and Popup -windows.
The problem with these elements is that they are disconnected from the visual tree of your window. Therefore, the DataContext not available. PlacementTarget is a reference to a visual tree element.
Basically, you will find the binding binding path, for example PlacementTarget.Tag , where in the source element the Tag property is set to DataContext , but in some situations the element itself also makes sense, for example, in your example.

Assuming the above code is used in ToolTip or ContextMenu , the DataContext will be set to the control that "owns" the element.

Look at the post from (Gishu +1) for an explanation of the mechanics.

+9
source

Each FrameworkElement has a DataContext , which is an arbitrary object. By default, the data binding source is a DataContext . You can use RelativeSource.Self to change the binding source to the FrameworkElement itself, and not its DataContext . Thus, the RelativeSource part simply moves you “one level” from the DataContext from FrameworkElement to FrameworkElement itself. When you are in FrameworkElement , you can specify the path to any of its properties. If the FrameworkElement is a Popup , it will have a PlacementTarget property, which is another FrameworkElement , which the Popup is relative to.

In short, if you have a Popup placed relative to the TextBox , for example, this expression sets the DataContext from the Popup to the TextBox and as a result {Binding Text} somewhere in the body of the Popup binds to the TextBox .

+6
source

This is the binding of the DataContext thing (UI Control? Need to see more code snippet) for the eigenvalue of the PlacementTarget property.

RelativeSource is used to indicate the source object relative to the binding target. The path property indicates the property name of the source object.

+3
source

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


All Articles