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
案例:下载 System.Windows.Interactivity.dll,引用后就可以直接使用如下的Interaction了。
1 <Button x:Name="SearchingButton"> 2 <i:Interaction.Triggers> 3 <i:EventTrigger EventName="MouseDown"> 4 <i:InvokeCommandAction Command="{Binding SearchCommand}" 5 CommandParameter="{Binding ElementName=SearchingTextBox,Path=Text}"/> 6 </i:EventTrigger> 7 </i:Interaction.Triggers> 8 </Button>
快捷键绑定
通过Key值,绑定ViewModel中相应命令
1 <UserControl.InputBindings> 2 <KeyBinding Key="Delete" Command="{Binding MenuDeleteCommand}" /> 3 </UserControl.InputBindings>
分类:
WPF/Silverlight
标签:
WPF
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)