【问题标题】:Command binding not working in a dynamic MVVM Context Menu命令绑定在动态 MVVM 上下文菜单中不起作用
【发布时间】:2012-01-01 09:31:30
【问题描述】:

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

从头开始,ContextMenuImage 的子代,当鼠标悬停在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>

TheCommand 属性定义如下:

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

【问题讨论】:

  • 您的MenuItemViewModelCollection 班级是什么样的?菜单项是否正确显示?

标签: wpf mvvm command contextmenu


【解决方案1】:

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

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

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

【讨论】:

  • 这正是我试图解决的问题,输出窗口上的提示非常有用。但我无法理解获取 DataContext 的层次结构。因为在我的情况下,它正在接收这样的内容 Content="{Binding Heading}" 但它无法接收命令 Command="{Binding DataContext.ItemSelectedCommand}" 所以我不得不使用 Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=DataContext.ItemSelectedCommand}"
【解决方案2】:

你试过了吗

Value="{TemplateBinding TheCommand}"?

【讨论】:

    【解决方案3】:

    看看我对以下问题的回答——

    Context Menu items command binding WPF using MVVM

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多