c# - MVVM 中的子菜单项选择

标签 c# wpf mvvm menu-items

我有以下 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");
    }
}       

现在这可以正常工作并显示我最近的菜单项,如下所示:

MenuItems

我的问题是; 如何绑定(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/

相关文章:

c# - 属性可以用于自动更改通知/记录吗?

c# - ZedGraph 自定义图表

c# - 为什么 ClipToBounds = false 不起作用?

mvvm - Xamarin View 在构造函数之后未从 viewModel 绑定(bind)

java - SQLite MVVM返回并获取Activity中的rowId

c# - 如何升级到 ASP.NET Core 2.0

c# - 如何在 WCF 服务上使用 Windows 身份验证访问服务器端的用户名?

wpf - 将标记扩展编写为嵌套元素

.net - 如何使按钮的宽度自动适应按钮的文本?

c# - 将依赖属性绑定(bind)到当前 DataContext 属性