Treeview context menu command not firing

2019-07-17 03:30发布

问题:

I have a treeview bound to a Observable collection of some property type. There is a HierarchicalDataTemplate that shows the data in treeview. Now i need to show specific context menu for each HierarchicalDataTemplate item.

I am using the following XAML to show context menu:

<HierarchicalDataTemplate ItemsSource="{Binding Collections}">
            <TextBlock Text="{Binding Path=Name}">
            <TextBlock.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Create" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.AddCommand}" CommandParameter="{Binding}"/>
                    </ContextMenu>
                </TextBlock.ContextMenu>
            </TextBlock>
        </HierarchicalDataTemplate>

Here the AddCommand is written in the view model that is bound to this under control.. I am able to see the context menu, but event is not firing on click on menu item.

Please help..

回答1:

Your command binding will not work because the ContextMenu is not on the same logical tree as your UserControl is, therefore it will not find the UserControl ancestor. However your ContextMenu should inherit its container's datacontext automatically. So this should work -

<ContextMenu>
      <MenuItem Header="Create" Command="{Binding AddCommand}" CommandParameter="{Binding}"/>
</ContextMenu>

However the AddCommand property should exist on your HierarchicalDataTemplate bound item.

EDIT:

If your Command is not defined in your HierarchicalDataTemplate's bound item and instead in your UserControl. Then another think you may try is giving your UserControl a name, and then bind the command to it by ElementName. Like this

Updated again:

<ContextMenu>
      <MenuItem Header="Create" Command="{Binding ElementName="MyUserControl" Path="DataContext.AddCommand"}" CommandParameter="{Binding}"/>
</ContextMenu>