WPF Binding parent property in HierarchicalDataTemplate

前提是你 提交于 2019-11-29 11:02:04

TemplatedParent only refers to the parent Control inside a ControlTemplate and so doesn't work with DataTemplates. You can use FindAncestor instead to locate the parent TreeViewItem and then access its DataContext.

Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}, AncestorLevel=2}, Path=DataContext.Ori}"

You have misunderstood the TemplatedParent binding in WPF. TemplatedParent refers to the inherited control that you are extending. Example: if I wrote a ControlTemplate that targeted a Button.

<ControlTemplate TargetType="{x:Type Button}" x:Key="MyButtonTemplate">
   <Border BorderBrush="{TemplateBinding Property=Background}" BorderThickness="3" >
      <ContentPresenter Margin="10"/>
   </Border>
</ControlTemplate>

This is binding the BorderBrush to the the base Button.Background property.

To achieve what you want, you need to walk the visual tree using the RelativeSource FindAncestor to find the parent and then perform the binding. To help try using either Mole WPF or Snoop.

Note: the copy of Snoop available above has some serious issues, i.e., cannot go more than 256-levels deep. I have a patched and feature extended version that is awesome. A interchange between using Mole and Snoop2 to debug/visualise during development.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!