命令绑定在动态 MVVM 上下文菜单中不起作用

2024-03-18

我是 WPF 新手。像许多其他人一样,我正在尝试绑定一个ContextMenu to an ObservableCollection创建动态上下文菜单。 除了绑定之外一切正常Command财产给TheCommand的财产MenuItemViewModel类,代表菜单项。该命令不会被触发。我究竟做错了什么?

从头开始,ContextMenu是 的孩子Image当鼠标悬停在Image.

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

其中空的 ContextMenu 定义如下:

<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>

The TheCommand属性定义如下:

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

ContextMenus 上的 DataContext 可能很奇怪,我敢打赌,如果您在调试时查看 Visual Studio 中的输出窗口,将会出现未找到 TheCommand 的绑定错误。请尝试以下操作:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

命令绑定在动态 MVVM 上下文菜单中不起作用 的相关文章

随机推荐