在WPF中设置Command命令的触发行为

1.在可点击的控件中比如:按钮 、单选框、复选框中绑定了command命令后,单击该控件会执行command命令,那么如何设置,双击或者键盘回车键触发command命令呢?

ViewModel:
public class MainViewModel { public Command Btn1Command { get; set; } public MainViewModel() { Btn1Command = new Command(); Btn1Command.DoExcute = Dobtn1Cmd; } private void Dobtn1Cmd(object obj) { int a = 0; } }

xaml:
<Grid> <StackPanel> <Button Content="btn1"> <Button.InputBindings > <MouseBinding Command="{Binding Btn1Command}" MouseAction="RightClick"></MouseBinding> </Button.InputBindings> </Button> </StackPanel> </Grid>
这里MouseAction 的行为总共7种,左键、右键、中键、滚轮滚动、左键双击、右键双击、中键双击,设置键盘触发要设置KeyBinding
2.在WPF中布局控件(如:grid)无法直接使用command进行命令绑定,只能通过事件的方式进行绑定 这里我们可以通过Behaviors实现
在WPF项目中添加NuGet包 :Microsoft.Xaml.Behaviors.Wpf
xmal:
<Window x:Class="WpfAppTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfAppTest" xmlns:b="http://schemas.microsoft.com/xaml/behaviors" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <b:Interaction.Triggers> <b:EventTrigger EventName="MouseMove"> <b:InvokeCommandAction Command="{Binding Btn1Command}"></b:InvokeCommandAction> </b:EventTrigger> </b:Interaction.Triggers> </Grid> </Window>

posted @ 2022-08-05 17:03  Wilson_it  阅读(1531)  评论(0编辑  收藏  举报