Treeview context menu command not firing

倖福魔咒の 提交于 2019-12-24 01:17:09

问题


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>


来源:https://stackoverflow.com/questions/9463589/treeview-context-menu-command-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!