WPF代码隐藏等效

DRa*_*app 3 c# wpf button code-behind

在开发时,我喜欢尝试理解的不仅仅是"只是这样做".特别是对于WPF,我喜欢从GUI(xaml)和代码隐藏中理解绑定的两个方面.话虽这么说,我想知道以下代码的等价物.

我有一个带有一些预定义的"ICommand"实例的ViewModel,例如添加,编辑,保存,取消,退出等等 - 它们按预期工作.现在,看看有一个按钮的View(Window)的绑定,我将它绑定到命令,类似于.

<Button Command="{Binding ExitCommand}" Content="Exit" ... />
Run Code Online (Sandbox Code Playgroud)

这恰当地完成了我希望允许表单退出(并做我正在玩的其他任何事情).

代码隐藏的后果是什么样的.我知道对于属性,例如IsEnabled或IsVisible绑定到依赖对象/属性,但是我不理解绑定到命令执行时的相关性.谢谢.

Rac*_*hel 5

您创建命令绑定的方式与后面的代码中的任何其他绑定相同.

例如,

Binding b = new Binding();
b.Source = myViewModel;
b.Path = new PropertyPath("ExitCommand");
MyButton.SetBinding(Button.CommandProperty, b);
Run Code Online (Sandbox Code Playgroud)

命令绑定期望绑定到类型的对象ICommand.当它们被执行时,例如按钮点击,它们首先调用ICommand.CanExecute(),如果是,则调用ICommand.Execute().如果CommandParameter设置属性,然后将其评估时使用CanExecuteExecute

对于具有Command绑定的WPF按钮,该IsEnabled属性将自动绑定到结果ICommand.CanExecute.CanExecute首次加载按钮时,该方法运行一次,并在命令绑定更改时随时再次运行.

如果您希望它更频繁地更新,例如CommandParameter更改时,您需要连接一些额外的内容以在CommandParameter更改时更新绑定.RelayCommands我看到的大多数都有内置的,比如MVVM Light RelayCommand,虽然其他命令如Microsoft PRISM DelegateCommand默认没有这种行为.