码迷,mamicode.com
首页 > Windows程序 > 详细

WPF 绑定Command

时间:2018-06-21 13:46:32      阅读:397      评论:0      收藏:0      [点我收藏+]

标签:TE   view   添加   eve   .com   转换   怎么   直接   AC   

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

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>

 

WPF 绑定Command

标签:TE   view   添加   eve   .com   转换   怎么   直接   AC   

原文地址:https://www.cnblogs.com/kybs0/p/9111327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!