WPF中提供了InvokeCommandAction可直接在前端xaml文件中触发Viewmodel中的事件,但该方法存在一个缺陷,只能通过CommandParameter传递参数,但不能传递鼠标事件参数。
- InvokeCommandAction的使用方法如下:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter" >
<i:InvokeCommandAction Command="{Binding FooCommand}" CommandParameter=abc/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
- 使用Mvvmlight中的EventToCommand, 可解决上述问题。Mvvmlight对System.Windows.Interactivity.dll的某些方面进行了扩展,能够传递事件参数,需要引用GalaSoft.MvvmLight.Extras.dll,实现如下:
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter" >
<cmd:EventToCommand Command="{Binding FooCommand}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>