WPF 代码隐藏等效项
在开发时,我喜欢尝试和理解更多的东西,而不仅仅是“这样做”。特别是对于 WPF,我喜欢从 GUI (xaml) 和隐藏代码来理解绑定的两个方面。话虽这么说,我想知道以下代码的等效代码是什么。
我有一个 ViewModel,其中包含一些预定义的“ICommand”实例,例如添加、编辑、保存、取消、退出等,并且它们按预期工作。现在,查看上面有一个按钮的视图(窗口)的绑定,我将它绑定到命令,类似的。
<Button Command="{Binding ExitCommand}" Content="Exit" ... />
这正确地实现了我所期望的允许表单退出(并执行我正在玩的其他操作)。
其背后的代码会是什么样子?我知道 IsEnabled 或 IsVisible 等属性绑定到依赖项对象/属性,但我不明白绑定到命令执行时的相关性。谢谢。
When developing, I like to try and understand more than "just do this". Especially with WPF, I like to understand BOTH aspects of the bindings... both from the GUI (xaml) and from the code-behind. That being said, I am wondering what the code equivalent would be for the following.
I have a ViewModel with some pre-defined "ICommand" instances, such as add, edit, save, cancel, exit, whatever -- and they work as expected. Now, looking at the binding of the View (Window) that has a button on it, I have it's binding to the commands, something like.
<Button Command="{Binding ExitCommand}" Content="Exit" ... />
and this properly does what I expect for allowing the form to exit (and do whatever else I'm playing with).
What would the code-behind look like for this. I know that with properties, such as IsEnabled or IsVisible are bound to dependency object / properties, but I don't understand the correlation when binding to a command's execution. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您创建命令绑定的方式与后面代码中任何其他绑定的方式相同。
例如,
命令绑定期望绑定到 ICommand 类型的对象。当它们被执行时,例如单击按钮时,它们首先调用
ICommand.CanExecute()
,如果是这样,则它们调用ICommand.Execute()
。如果设置了CommandParameter
属性,则在评估CanExecute
和Execute
时使用该属性对于具有命令绑定的 WPF 按钮,
IsEnabled
属性自动绑定到ICommand.CanExecute
的结果。CanExecute
方法在按钮首次加载时运行一次,并在命令绑定更改时再次运行。如果您希望它更频繁地更新,例如当
CommandParameter
更改时,您需要连接一些额外的东西来在CommandParameter
更改时更新绑定。我看到的大多数RelayCommands
都具有此内置功能,例如 MVVM Light 的RelayCommand
,尽管其他命令(例如 Microsoft PRISM 的DelegateCommand
)没有此行为默认情况下。You create the Command Binding the same way you would any other binding in code behind.
For example,
Command bindings expect to be bound to an object of type
ICommand
. When they get executed, such as on a Button Click, they first callICommand.CanExecute()
and if that is true then they callICommand.Execute()
. If theCommandParameter
property is set then that is used when evaluatingCanExecute
andExecute
With WPF Buttons that have a Command binding, the
IsEnabled
property is automatically bound to the result ofICommand.CanExecute
. TheCanExecute
method is run once when the button is first loaded, and run again anytime the Command Binding changes.If you want it to update more frequently, such as when the
CommandParameter
changes, you need to hook up something extra to update the binding when theCommandParameter
changes. MostRelayCommands
I see have this built-in, such as MVVM Light'sRelayCommand
, althought other commands such as Microsoft PRISM'sDelegateCommand
do not have this behavior by default.