WPF命令绑定汇总
1、Button等自带Command属性的控件,直接绑定命令
<Button HorizontalAlignment="Left" Width="105" Height="32"Command="{Binding ClickCommand}"> <TextBlock Text="点击" Foreground="#555555"></TextBlock> </Button>
2、Microsoft.Xaml.Behaviors.Wpf包,可通过Nuget获取
添加引用
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
XAML中调用:
<b:Interaction.Triggers> <b:EventTrigger EventName="Loaded"> <b:InvokeCommandAction Command="{Binding LoadedCommand}" PassEventArgsToCommand="True"></b:InvokeCommandAction> </b:EventTrigger> </b:Interaction.Triggers>
3、System.Windows.Interactivity.WPF包,可通过Nuget获取(和第二种方式类似)
添加引用
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
或者
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
XAML中调用:
<i:Interaction.Triggers> <i:EventTrigger EventName="MouseMove"> <i:InvokeCommandAction Command="{Binding Command2}" CommandParameter="{Binding ElementName=btn}" /> </i:EventTrigger> </i:Interaction.Triggers>
4、KeyBinding,用来绑定鼠标、键盘点击事件
<Window.InputBindings> <KeyBinding Key="Enter" Command="{Binding SendCommand}" /> </Window.InputBindings>