我有以下 XAML 用于填充带有最近文档的子菜单项列表:
<MenuItem Header="_Recent Studies"
ItemsSource="{Binding RecentFiles}"
AlternationCount="{Binding Path=Items.Count,
Mode=OneWay,
RelativeSource={RelativeSource Self}}"
ItemContainerStyle="{StaticResource RecentMenuItem}"/>
在 ViewModel 我有以下
RecentFiles
属性(property)private ObservableCollection<RecentFile> recentFiles = new ObservableCollection<RecentFile>();
public ObservableCollection<RecentFile> RecentFiles
{
get { return this.recentFiles; }
set
{
if (this.recentFiles == value)
return;
this.recentFiles = value;
OnPropertyChanged("RecentFiles");
}
}
现在这可以正常工作并显示我最近的菜单项,如下所示:
我的问题是; 如何绑定(bind)到最近文件的点击事件
MenuItem
年代? 我很容易使用AttachedCommands
但我不明白这是如何实现的。谢谢你的时间。
最佳答案
如果您使用的是 MVVM 模式,则根本不需要 Click 事件。
您应该使用 MenuItem.Command属性以便与您的 ViewModel 进行通信。
如何?
如我所见,您正在使用 ItemContainerStyle。您可以将以下行添加到该样式:
<Style x:Key="RecentMenuItem" TargetType="MenuItem">
...
<Setter Property="Command" Value="{Binding Path=SelectCommand}" />
...
</Style>
在您的
RecentFile
: public ICommand SelectCommand { get; private set; }
您可以在
RecentFile
的构造函数中初始化命令类(class)。
关于c# - MVVM 中的子菜单项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364477/