我已经阅读了 Josh Smiths 关于使用 RelayCommand 将命令绑定到视图模型的文章。但是我需要将 ApplicationCommands.Save 绑定到视图模型,以便当用户单击保存菜单项时,它会在窗口中处理。这怎么可能?
5 回答
我知道我们使用服务的最佳解决方案。例如,像这样的 ICommandBindingsProvider:
public interface ICommandBindingsProvider
{
CommandBindingCollection CommandBindings { get; }
}
这将被注入您的 ViewModel 并像这样使用:
public MyViewModel(ICommandBindingsProvider commandBindings)
{
commandBindings.Add(new CommandBinding(....));
}
服务的注入方式将取决于您使用的 MVVM 框架。大多数(但不是全部)都支持某种服务注入功能。如果您需要更具体的代码示例,请查看执行服务注入的Onyx并提供执行此操作的服务。
有一个很好的教程可以帮助绑定应用程序命令。
- 为视图设置命令绑定集合以在视图模型中绑定。例如:
public CommandBindingCollection CommandBindings { get; } public YourViewModel() { //Create a command binding for the save command var saveBinding = new CommandBinding(ApplicationCommands.Save, SaveExecuted, SaveCanExecute); //Register the binding to the class CommandManager.RegisterClassCommandBinding(typeof(YourViewModel), saveBinding); //Adds the binding to the CommandBindingCollection CommandBindings.Add(saveBinding); }
设置附加属性。阅读有关如何做到这一点的文章。
然后使用附加属性绑定到它。
<UserControl local:AttachedProperties.RegisterCommandBindings="{Binding CommandBindings}"> <Window.DataContext> <local:YourViewModel></local:YourViewModel> </Window.DataContext> </UserControl>
您的保存菜单项是如何创建的?它必须在某个地方绑定到 ApplicationCommands.Save?您可以更改它,以便它绑定到您的 ViewModel 的保存。
或者,您将保存命令绑定放在视图模型上,然后对其进行数据绑定,类似于(伪代码)
在视图模型中:
...
public Command SaveCommand { get { return yourCodeHere; } }
...
在视图中:
<Button Command="{Binding Path=SaveCommand}" Content="Click"/>
更新:我刚刚尝试绑定到命令绑定中的命令,但它不起作用。我在想的是绑定到一个命令。
我过去曾成功使用过这种方法:
首先在 ViewModels 上定义一个 CommandBindings 属性(与在 Views 上的定义相同)。
然后对于 ViewModel 实现的每个 Command,在 ViewModel 的 CommandBindings 中添加一个 CommandBinding。
然后,当你设置:
view.DataSource = viewModel;
还设置:
view.CommandBindings.AddRange(viewModel.CommandBindings);
我认为可以使用 CommandBindings 属性的绑定来完成(无法确定)。