【发布时间】:2011-08-21 19:43:33
【问题描述】:
我现在正在开发我的第一个大型 WPF MVVM 应用程序,它使用 MVVM Light Toolkit 和 Josh Smith 的 RelayCommand。 我遇到的问题是我将此命令绑定到 ContextMenu 中的一个项目,该项目一直处于禁用状态。
这里是 MenuItem 的代码 sn-p:
<MenuItem
Header="Verwijderen"
Command="{StaticResource DeleteNoteCommandReference}"
CommandParameter="{Binding}" />
现在我对命令绑定所做的工作如下:我使用了一个名为 CommandReference 的类,我找到了 here。
这是命令引用本身:
<command:CommandReference
x:Key="DeleteNoteCommandReference"
Command="{Binding DeleteNoteCommand}" />
我这样做的原因是我注意到 ContextMenu 上的命令绑定问题(因为 ContextMenu 不是逻辑/可视树的一部分)。我在网上找到了几个关于这个主题的主题,其中一些我发现了 CommandReference 类,这似乎是解决我问题的好方法。 这些命令绑定问题确实消失了,但我的命令的 CanExecute 似乎无法识别,或者因为 MenuItem 一直处于禁用状态。
在 ViewModel(作为其 DataContext 绑定到视图)中,我有以下命令代码:
/// <summary>
/// Command for deleting a note.
/// </summary>
public RelayCommand<NoteViewModel> DeleteNoteCommand {
get;
private set;
}
/// <summary>
/// CanExecute method for the DeleteNoteCommand.
/// </summary>
/// <param name="note">The NoteViewModel that CanExecute needs to check.</param>
/// <returns>True if the note can be deleted, false otherwise.</returns>
public bool DeleteNoteCommandCanExecute(NoteViewModel note) {
return Notes.Contains(note);
}
/// <summary>
/// Creates all commands for this ViewModel.
/// </summary>
private void CreateCommands() {
DeleteNoteCommand = new RelayCommand<NoteViewModel>(param => DeleteNote(param), param => DeleteNoteCommandCanExecute(param));
}
我在这里缺少什么来使我的代码正常工作? 我认为这可能与我正在使用的 CommandReference 有关,但我不知道要查找什么。
真的希望你们能帮忙!
【问题讨论】:
标签: c# wpf mvvm relaycommand canexecute