【问题标题】:Sub-MenuItem Selection in MVVMMVVM 中的子菜单项选择
【发布时间】:2013-10-15 00:46:40
【问题描述】:

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

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

我的问题是; 如何绑定到我最近使用的文件MenuItems 上的点击事件? 我可以使用AttachedCommands,但我不知道如何实现。

感谢您的宝贵时间。

【问题讨论】:

    标签: c# wpf mvvm menu-items


    【解决方案1】:

    如果您使用的是 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类的构造函数中初始化命令。

    【讨论】:

    • 是的,但是怎么做?那的问题。我遇到问题的原因是这些项目是在运行时填充的......
    • 啊当然。愚蠢。但是,要使绑定以您需要的样式工作:&lt;Setter Property="Command" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}, Path=DataContext.LoadRecentResourceSet}" /&gt;。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多