Treeview上下文菜单命令未触发 [英] Treeview context menu command not firing

查看:47
本文介绍了Treeview上下文菜单命令未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到某些属性类型的Observable集合的树视图.有一个HierarchicalDataTemplate,它在树视图中显示数据.现在,我需要为每个HierarchicalDataTemplate项目显示特定的上下文菜单.

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.

我正在使用以下XAML显示上下文菜单:

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>

在此处,AddCommand是在受其约束的视图模型中编写的.我能够看到上下文菜单,但是单击菜单项时未触发事件.

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.

请帮助.

推荐答案

您的命令绑定将不起作用,因为ContextMenu与UserControl不在同一逻辑树上,因此找不到UserControl的祖先.但是,您的ContextMenu应该自动继承其容器的datacontext.所以这应该工作-

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>

不过,您的HierarchicalDataTemplate绑定项上应该存在AddCommand属性.

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

如果未在HierarchicalDataTemplate的绑定项目中而是在UserControl中定义了Command.然后,另一个您可以尝试的方法是为UserControl命名,然后通过ElementName将命令绑定到该名称.像这样

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

再次更新:

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

这篇关于Treeview上下文菜单命令未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆