How do I use WPF bindings with RelativeSource?

前端 未结 13 1978
执念已碎
执念已碎 2020-11-22 03:00

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

13条回答
  •  孤独总比滥情好
    2020-11-22 03:41

    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}
    

提交回复
热议问题