任意控件的事件绑定到Command
MVVM模式下,大多控件是没有Command属性的,将这些控件的任意事件绑定到ViewModel中的Command,可以使用Blend提供的一个程序集System.Windows.Interactivity和MvvmLight的EventToCommand具体做法如下:
先引用命名空间:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
再添加代码:
<i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <cmd:EventToCommand Command="{Binding OnStep2Loaded}" /> </i:EventTrigger> </i:Interaction.Triggers>
上面的代码将父控件的Loaded事件绑定到OnStep2Loaded Command上。使用System.Windows.Interactivity中的InvokeCommandAction也可以实现相同的功能,但不能传递EventArgs,Mvvmlight的EventToCommand却可以传递RoutedEventArgs对象。
另外Blend还提供了一个在Xaml中直接调用对象方法等类,在Microsoft.Expression.Interactions中命名空间:
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"