Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding parent property in HierarchicalDataTemplate

I have a WPF TreeView with 2 levels of data and 2 HierarchicalDataTemplate to format each level. From the HierarchicalDataTemplate at the second level, I need to bind a property in the class of the first level. I have tried in this way, but it dosn't work:

Text="{Binding Path=Ori, RelativeSource={RelativeSource TemplatedParent}}"

with Ori as the name of the propery

Even in this way it dosn't works:

Text="{Binding Path=tOri, RelativeSource={RelativeSource TemplatedParent}}"

with tOri as the name of the TextBlock in the fisrt HierarchicalDataTemplate that bind the Ori propery.

Can you help me?

like image 733
lamarmora Avatar asked Jul 15 '10 12:07

lamarmora


1 Answers

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}"
like image 125
John Bowen Avatar answered Sep 19 '22 22:09

John Bowen