WPF中不是所有的控件都有Command属性的,如果窗体我需要在ViewModel中处理Loaded事件命令,或者其他事件的命令时,很难都过绑定Command完成,必须要注册依赖属性或事件等,太麻烦了。我喜欢简约、有效的方式,现在我和大家一起分享一下。
场景,我需要处理Button的Click和MouseMove事件,但又避免用后置代码,尽量要在ViewModel中获取。单独一个Click可以通过Button的Command来完成,在前两篇文章中我已介绍过,现在就来处理MouseMove事件,这是需要一个System.Windows.Interactivity.dll,该dll是安装Blend后才有的,在C:\Program Files\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries目录中,然后我们仍需要Prism.dll。
xaml:
<Window x:Class="MVVMCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MVVMCommand"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Button Name="btn" Content="Button">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding ButtonCommand1}"
CommandParameter="20"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseMove">
<i:InvokeCommandAction Command="{Binding ButtonCommand2}"
CommandParameter="{Binding ElementName=btn}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</Window>
注意;xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"就是导入Blend的dll,然后在控件内部用<i:Interaction.Triggers/>即可,其它应该一看就知道,我通过事件触发器,来引发ViewModel中两个Command,第二个Command的参数是Button对象,通过ElementName=btn来指定。
ViewModel:
namespace MVVMCommand{
public class MainWindowViewModel{
public ICommand ButtonCommand1{
get{
return new DelegateCommand<string>((str) =>{
MessageBox.Show("ButtonCommand1 with Parameter: " + str);
});
}
}
public ICommand ButtonCommand2{
get{
return new DelegateCommand<Button>((btn) =>{
Point p = Mouse.GetPosition(btn);
btn.Content = string.Format("{0},{1}", p.X, p.Y);
});
}
}
}
}


