我现在正在开发我的第一个大型 WPF MVVM 应用程序,它使用 MVVM Light Toolkit 和 Josh Smith 的 RelayCommand。我遇到的问题是我将此命令绑定到 ContextMenu 中的一个项目,该项目一直处于禁用状态。
这是 MenuItem 的代码片段:
<MenuItem
Header="Verwijderen"
Command="{StaticResource DeleteNoteCommandReference}"
CommandParameter="{Binding}" />
现在我对命令绑定所做的如下:我使用了一个名为 CommandReference 的类,我在这里找到了它。
这是命令引用本身:
<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 有关,但我不知道要查找什么。
真心希望大家帮忙!