문제

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;
    }
}
도움이 되었습니까?

해결책

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}}}"/>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top