WPF 绑定Command

WPF中,我们使用MVVM,在ViewModel中定义Command和其业务逻辑,界面绑定Command。

那么是不是所有的事件都可以定义Command呢,然后将业务全部放在ViewModel中呢?

界面CommandBindings

如果只是交互的处理,可以直接定义RoutedCommand即可

1. 定义Command

<RoutedCommand x:Key="SelectAllCommand"/>

 

2. 添加命令委托处理

<UserControl.CommandBindings>
     <CommandBinding Command="{StaticResource  SelectAllCommand}" Executed="SelectAllExecuted"/>
</UserControl.CommandBindings>

3. 绑定Command

<CheckBox Name="AllSelectCheckBox" Command="{StaticResource SelectAllCommand}" />

 

InvokeCommandAction

控件不只有Button,还有其它很多TextBox/ListBox等控件甚至自定义控件的KeyDown/MouseUp/LostFocus等事件以及自定义的事件。

我们都知道Buttton有Command属性(对应Click事件),直接绑定相应的Command就可以了,那么除Button.Click事件之外的事件怎么绑定?

CommandAction是Trigger与Command的中间转换器

通过InvokeCommandAction 的使用,WPF任意事件都可以绑定Command,将业务逻辑放在ViewModel中。如:

 

 <TextBlock>
     <i:Interaction.Triggers>
         <i:EventTrigger EventName="MouseLeftButtonDown">
             <i:InvokeCommandAction Command="{Binding MouseLeftButtonDownCommand}"/>
         </i:EventTrigger>
     </i:Interaction.Triggers>
 </TextBlock>

 

 

 快捷键绑定

通过Key值,绑定ViewModel中相应命令

 <UserControl.InputBindings>
     <KeyBinding Key="Delete" Command="{Binding MenuDeleteCommand}" />
 </UserControl.InputBindings>

 

转自:https://www.e-learn.cn/content/net/800987

posted @   wzwyc  阅读(744)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示