WPF的有些UI元素有Command属性能够直接实现绑定,如Buttonweb
可是不少Event的触发如何绑定到ViewModel中的Command呢?app
答案就是使用EventTrigger能够实现。mvvm
继续上一篇对Slider的研究,在View中修改Interaction.ide
<i:Interaction.Triggers> <i:EventTrigger EventName="ValueChanged"> <i:InvokeCommandAction Command="{Binding ValueChangedCommand}" /> </i:EventTrigger> </i:Interaction.Triggers>
那么若是将EventName修改成Thumb.DragCompleted 后发现这个事件并不会被触发
缘由是:Because the command is hooked up to the Slider, but the event is fired on the Thumb。spa
(参考:http://stackoverflow.com/questions/14331272/issue-with-thumb-dragstarted-event-with-mvvmlight)code
参考上述连接中Tom Allen的方法后能够实现, 可是这个方法并无很好的遵照MVVM模式。orm
因而接着研究,既然DragCompleted是挂在Thumb上面的,那么为什么不直接和Thumb 绑定呢?blog
修改Slider的ControlTemplate, 在Track控件中的Thumb中绑定Event 成功!事件
<UserControl.Resources> <ControlTemplate x:Key="trackThumb" TargetType="{x:Type Slider}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Grid> <Track x:Name="PART_Track"> <Track.Thumb> <Thumb Width="10"> <i:Interaction.Triggers> <i:EventTrigger EventName="DragCompleted"> <i:InvokeCommandAction Command="{Binding ValueChangedCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> </Thumb> </Track.Thumb> </Track> </Grid> </Border> </ControlTemplate> </UserControl.Resources>
参考:ci
http://www.codeproject.com/Articles/274982/Commands-in-MVVM#example9