【发布时间】:2018-07-08 10:32:31
【问题描述】:
在研究了几个Q&A on stackoverflow, some tutorials 当然还有official documentation之后,我尝试使用987654331@ 在我的 WPF Prism MVVM 应用程序中。
我目前的做法
在尝试了不同的解决方案后,我发现了以下星座:
-
我正在使用this answer中提到的
AttachCommandBindingsBehavior类,在视图中会这样使用:<UserControl> <i:Interaction.Behaviors> <localBehaviors:AttachCommandBindingsBehavior CommandBindings="{Binding CommandBindings}"/> </i:Interaction.Behaviors> </UserControl> -
MyViewModel包含一个CommandBindingCollection属性,将在构造函数中填充:public CommandBindingCollection CommandBindings { get; } = new CommandBindingCollection(); public MyViewModel() { this.CommandBindings.AddRange(new[] { new CommandBinding(ApplicationCommands.Save, this.Save, this.CanSave), new CommandBinding(ApplicationCommands.Open, this.Open) }); } -
UserControl
MyView包含两个按钮:<Button Command="ApplicationCommands.Open" Content="Open" /> <Button Command="ApplicationCommands.Save" Content="Save" />
我的第一个问题此时是:Executed() 和 CanExecute() 方法是否已经绑定到 Button 的 Command-DependencyProperty?既然不行,那我是不是忘了什么或者做错了什么?
我的第二个问题是:如何触发按钮绑定的命令的CanExecute?实际用例:MyViewModel.CanSave() 返回 true,当用户成功执行 MyViewModel.Open() 方法时。通常,我会调用DelegateCommand.RaiseCanExecuteChanged(),但调用ApplicationCommands.Save.RaiseCanExecuteChanged() 不会执行MyViewModel.CanSave()。
请随时询问更多信息。我将非常感谢您的回答。谢谢!
【问题讨论】: