【问题标题】:Treeview context menu command not firing树视图上下文菜单命令未触发
【发布时间】:2012-02-27 10:38:27
【问题描述】:

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

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

<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 写在视图模型中,该视图模型绑定到 this 受控制.. 我能够看到上下文菜单,但单击菜单项时未触发事件。

请帮忙..

【问题讨论】:

    标签: wpf treeview contextmenu


    【解决方案1】:

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

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

    但是,您的 HierarchicalDataTemplate 绑定项上应该存在 AddCommand 属性。

    编辑:

    如果您的 Command 未在 HierarchicalDataTemplate 的绑定项中定义,而是在您的 UserControl 中定义。然后您可能会尝试的另一个想法是给您的 UserControl 一个名称,然后通过 ElementName 将命令绑定到它。像这样

    再次更新:

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

    【讨论】:

    • 如果 AddCommand 的属性不在 HierarchicalDataTemplate 的绑定项中,这将不起作用。是这样吗?
    • 这也可以。我正在使用 MVVM 模式。添加命令在视图模型中定义。
    • 哪个视图模型? HierarchicalDataTemplate 中的数据上下文不是您为用户控件定义的主视图模型。但是我再次更新了我的答案。尝试使用新的。
    • 具有 HierarchicalDataTemplate 的用户控件的视图模型。使用更新的答案仍然可以触发事件。
    • 如果没有更多信息,很难知道到底是什么问题。如果您可以从定义命令的 UserControl 的 ViewModel 中发布相关的代码,那就太好了。另外,您是否尝试使用 snoop 来诊断问题?
    猜你喜欢
    • 2023-04-01
    • 2012-11-06
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多