Question

i have tree view that has two levels, in the second level i have template with a context menu inside, and i'm trying to pass the TreeViewItem the ContextMenu belongs to as a CommandParameter, and so far no success, in my app the TreeviewItem has a HierarchicalDataTemplate but here is a simplified example for my XAML:

<Grid
    Background="Transparent">
    <TreeView>
        <TreeViewItem Header="blabla1"/>
        <TreeViewItem Header="blabla2">
            <TreeViewItem Header="innerblalbla">
                <TreeViewItem.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Test" 
                                  Command="{Binding PlacementTarget.DataContext.testCommand,
                       RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenuu}}}"
                                   CommandParameter=??????/>
                    </ContextMenu>
                </TreeViewItem.ContextMenu>
            </TreeViewItem>
        </TreeViewItem>
    </TreeView>
</Grid>

and my viewModel(DataContext is set in code behind):

class myViewModel : INotifyPropertyChanged
{

    public myViewModel()
    {
        testCommand = new DelegateCommand(test);
    }

    public DelegateCommand testCommand { get; set; }

    private void test()
    {
        var x = 1;
    }
}
Was it helpful?

Solution

MenuItem doesn't lie in same Visual Tree as that of TreeViewItem, that's why FindAncestor is not able to travel till Window.

You can use PlacementTarget of ContextMenu to get TreeViewItem which will inherit DataContext of window automatically.

This is how you do it:

<MenuItem Header="Test" 
          Command="{Binding PlacementTarget.DataContext.testCommand,
                            RelativeSource={RelativeSource Mode=FindAncestor, 
                                           AncestorType={x:Type ContextMenu}}}"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top