命令绑定在动态MVVM上下文菜单中不起作用 [英] Command binding not working in a dynamic MVVM Context Menu

查看:72
本文介绍了命令绑定在动态MVVM上下文菜单中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF的新手。像许多其他人一样,我试图将 ContextMenu 绑定到 ObservableCollection 来创建动态上下文菜单。
除了将 Command 属性绑定到 MenuItemViewModel的 TheCommand 属性之外,其他所有操作均有效类,代表菜单项。该命令未触发。我在做什么错了?

I am new to WPF. Like many others, I am trying to bind a ContextMenu to an ObservableCollection to create a dynamic context menu. Everything works except binding the Command property to the TheCommand property of the MenuItemViewModel class, that represents the menu item. The command is not fired. What am I doing wrong?

从头开始, ContextMenu 是<$ c的子级$ c>图片,并且当鼠标悬停在图片上时显示。

To start from the beginning, the ContextMenu is a child of the Image and is shown when the mouse is over the Image.

 <Image.ContextMenu >
        <ContextMenu ItemsSource="{DynamicResource ContextMenu}"

其中定义了空的ContextMenu如下:

where the empty ContextMenu is defined as follows:

<Window.Resources>
    <local:MenuItemViewModelCollection x:Key="ContextMenu">
    </local:MenuItemViewModelCollection>

    <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}"
                                      ItemsSource="{Binding Path=Children}">
        <HierarchicalDataTemplate.ItemContainerStyle>
            <Style TargetType="MenuItem">
                <Setter Property="Command"
                    Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}},
                                    Path=DataContext.TheCommand}"/>
              <!--  Value="{Binding Path=TheCommand}" /> I tried this too -->

            </Style>
        </HierarchicalDataTemplate.ItemContainerStyle>
    </HierarchicalDataTemplate>
</Window.Resources>

TheCommand 属性的定义如下:

public class MenuItemViewModel : INotifyPropertyChanged
{
       //...
       public ICommand TheCommand
       {
             //...
       }
}


推荐答案

ContextMenus上的DataContext可能很奇怪,我敢打赌,如果您在调试Visual Studio的输出窗口时调试了TheCommand的绑定错误,被发现。请尝试以下操作:

DataContext on ContextMenus can be weird, I bet if you look in the output window in Visual Studio when debugging that there will be a binding error for TheCommand not being found. Try the following:

<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.DataContext.TheCommand}"/> 

这将使用启动ContextMenu的元素的DataContext,而不是上下文菜单本身。

This will use the DataContext of the element that the ContextMenu is launched from, not the context menu itself.

这篇关于命令绑定在动态MVVM上下文菜单中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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