我正在研究我的第一个大型WPF MVVM应用程序,它将MVVM Light Toolkit与Josh Smith的RelayCommand结合使用。 我遇到的问题是我将此命令绑定到ContextMenu中的一个项目,该项目始终处于禁用状态。为什么绑定到RelayCommand的ContextMenu项总是被禁用?
这里的菜单项的代码片段:
<MenuItem
Header="Verwijderen"
Command="{StaticResource DeleteNoteCommandReference}"
CommandParameter="{Binding}" />
现在我已经与做的CommandBinding是这样的:我使用了一种叫做CommandReference类,我发现here。
这是commandreference本身:
<command:CommandReference
x:Key="DeleteNoteCommandReference"
Command="{Binding DeleteNoteCommand}" />
为什么我这样做是因为问题上的CommandBinding一个ContextMenu,我注意到(所造成的事实,即一个ContextMenu不是的部分原因逻辑/可视化树)。我在网上发现了关于这个主题的几个主题,其中一些发现了CommandReference类,这似乎是我的问题的一个很好的解决方案。 这些命令绑定问题确实消失了,但看起来我的命令CanExecute无法识别,或者因为MenuItem保持禁用状态。
在视图模型(这势必将视图作为其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有关,但我不知道要寻找什么。
真的希望你们能帮忙!
感谢您的建议,但并没有调用断点......我在其他地方了解了这个InvalidateRequerySuggested方法,但我应该在哪里调用它?在构建我的视图时? – Thomas
理论上你应该在条件改变或可能改变时调用它。 (The Notes.Contains(note))。 – aKzenT
对于Bug跟踪,请尝试将它放在不同的地方(例如,当上下文菜单弹出时),看看它是否有所作为。但我认为你的问题是命令参数,因为你正在使用绑定,但上下文菜单不是可视化树的一部分。奇怪的是,断点从来没有被打... – aKzenT