0

I have a ContextMenu linked to a TreeViewItem linked to a parent TreeViewItem :

    TreeView
        TreeViewItemParent
            TreeViewItem : ContextMenu here
            TreeViewItem
        TreeViewItemParent
        ...

My ContextMenu is a "Move to..." menu and contains a list of MenuItem. My ContextMenu :

<ContextMenu x:Key="ContextMoveItem">
    <MenuItem x:Name="MoveItem" Header="Move..." Click="MoveItem_Click"/>
</ContextMenu>

I Need to get The TreeViewItemParent Header when I click on my MenuItems :

private void MoveItem_Click(object sender, RoutedEventArgs e){
    var MenuItem = (MenuItem)sender;
    //Need to get the header of the parent TreeViewItem here
}
Hyro
  • 23
  • 4
  • Why would you want to get header of parent `TreeViewItem` on menu click? You probably want to access some data which view shows as it? Look into MVVM. Design ViewModel properly, then the menu command can access underlying data directly to find parent without need to use visual tree for this. – Sinatr Nov 22 '17 at 12:18
  • If you insist, then you can use `PlacementTarget` (see [this answer](https://stackoverflow.com/a/11339065/1997232)) to find owner of menu and then [find parent](https://www.infragistics.com/community/blogs/blagunas/archive/2013/05/29/find-the-parent-control-of-a-specific-type-in-wpf-and-silverlight.aspx). – Sinatr Nov 22 '17 at 12:21
  • I dont use MVVM here maybe I should have.. By navigation in the MenuItem sender I founded : ```string test = ((HeaderedItemsControl)((FrameworkElement)((Visual)((Visual)((Visual)((FrameworkElement)((Visual)((FrameworkElement)((ContextMenu)MenuItem.Parent).PlacementTarget).TemplatedParent).VisualParent).Parent).VisualParent).VisualParent).VisualParent).TemplatedParent).Header.ToString();``` I have paste this path in a var and it tell me that it isnt possible to access the first VisualParent prop from the Visual class... – Hyro Nov 22 '17 at 12:57
  • That's not the right way to find parent. – Sinatr Nov 22 '17 at 13:03
  • ```var Menu = (MenuItem)sender; MenuItem mnu = FindParent(Menu);``` Returns me null (using the FindParent method that you have linked). – Hyro Nov 22 '17 at 13:13
  • You need `FindParent(currentTreeViewItem)` where `currentTreeViewItem` is obtained in complicated way, explained earlier (you can't use `MenuItem`, because menu is not a part of visual tree). – Sinatr Nov 22 '17 at 13:18

0 Answers0