1

我有以下 XAML 用于填充带有最近文档的子菜单项列表:

<MenuItem Header="_Recent Studies" 
          ItemsSource="{Binding RecentFiles}"
          AlternationCount="{Binding Path=Items.Count, 
                                     Mode=OneWay, 
                                     RelativeSource={RelativeSource Self}}" 
          ItemContainerStyle="{StaticResource RecentMenuItem}"/>

在 ViewModel 我有以下RecentFiles属性

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");
    }
}       

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

菜单项

我的问题是;如何绑定到最近文件MenuItem的点击事件?我很容易使用AttachedCommands,但我不知道如何实现。

谢谢你的时间。

4

1 回答 1

2

如果您使用的是 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

于 2013-10-14T16:17:43.130 回答