【发布时间】:2012-01-01 09:31:30
【问题描述】:
我是 WPF 新手。像许多其他人一样,我正在尝试将ContextMenu 绑定到ObservableCollection 以创建动态上下文菜单。
除了将Command 属性绑定到代表菜单项的MenuItemViewModel 类的TheCommand 属性之外,一切正常。该命令未触发。我做错了什么?
从头开始,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>
TheCommand 属性定义如下:
public class MenuItemViewModel : INotifyPropertyChanged
{
//...
public ICommand TheCommand
{
//...
}
}
【问题讨论】:
-
您的
MenuItemViewModelCollection班级是什么样的?菜单项是否正确显示?
标签: wpf mvvm command contextmenu