WPF 绑定Command方式

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

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

界面CommandBindings

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

1. 添加Command

1 <RoutedCommand x:Key="SelectAllCommand"/> 

2. 添加命令委托处理

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

3. 绑定Command

1 <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中。如:

自定义Command,请参考https://www.cnblogs.com/kybs0/p/7523654.html

1 <TextBlock>
2     <i:Interaction.Triggers> 3 <i:EventTrigger EventName="MouseLeftButtonDown"> 4 <i:InvokeCommandAction Command="{Binding MouseLeftButtonDownCommand}"/> 5 </i:EventTrigger> 6 </i:Interaction.Triggers> 7 </TextBlock>

 快捷键绑定

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

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

 

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值