我正在开发我的第一个大型WPF MVVM应用程序,它使用MVVM Light Toolkit与Josh Smith的RelayCommand结合使用。 我遇到的问题是我将此命令绑定到ContextMenu中的一个项目,该项目始终处于禁用状态。
这是MenuItem的代码片段:
<MenuItem
Header="Verwijderen"
Command="{StaticResource DeleteNoteCommandReference}"
CommandParameter="{Binding}" />
现在我使用commandbinding完成了以下操作:我使用了一个名为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有关,但我不知道该寻找什么。
真的希望你们能帮忙!
答案 0 :(得分:0)
尝试在DeleteNoteCommandCanExecute
内设置断点并检查:
DeleteNoteCommandCanExecute
内的代码不会抛出异常(例如note
参数为null)在第一种情况下,如果未调用,请尝试调用InvalidateRequerySuggested
上的CommandManager
方法强制重新查询CanExecute
方法。