开发者

WPF binding with PlacementTarget and RelativeSource

开发者 https://www.devze.com 2023-02-10 17:53 出处:网络
开发者_JAVA百科Can you explain the following WPF code: DataContext=\"{Binding Path=PlacementTarget,RelativeSource={x:Static RelativeSource.Self}}\">

开发者_JAVA百科Can you explain the following WPF code:

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

I find it extremely confusing. What is placement target and what is relative source?


This 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 is not available. The PlacementTarget is a link to an element of the visual-tree.
Mostly you will find a binding path like PlacementTarget.Tag where in the source element the Tag property has been set to the DataContext but in some situations, the element itself is also meaningful, such as in your example.

Assuming that the above code is used in a ToolTip or a 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.


Every FrameworkElement has a DataContext that is an arbitrary object. The default source for a data binding is that DataContext. You can use RelativeSource.Self to change the source for a binding to the FrameworkElement itself instead of its DataContext. So the RelativeSource part just moves you "up one level" from the DataContext of the FrameworkElement to the FrameworkElement itself. Once you are at the FrameworkElement you can specify a path to any of its properties. If the FrameworkElement is a Popup, it will have a PlacementTarget property that is the other FrameworkElement that the Popup is positioned relative to.

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


This is binding the DataContext of a thing (UI Control? need to see more of the code snippet ) to its own PlacementTarget property value.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消