如何使用WPF绑定使用的RelativeSource?绑定、如何使用、WPF、RelativeSource

2023-09-02 10:15:03 作者:Insist

我如何使用的RelativeSource 与WPF绑定,什么是不同的使用情况?

How do I use RelativeSource with WPF bindings and what are the different use-cases?

推荐答案

如果您要绑定的对象上的其他属性:

If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

如果你想获得一个属性的祖先:

If you want to get a property on an ancestor:

{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

如果你想获得对模板化父属性(这样你就可以在一个控件模板做双向绑定)

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

或短(这仅适用于单向绑定):

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}