1

次の XAML を使用して、sub-MenuItem リストに RecentDocuments を設定しています。

<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 イベントはまったく必要ありません。

ViewModel と通信するには、MenuItem.Commandプロパティを使用する必要があります。

どうやって?

ご覧のとおり、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 に答える