(WPF, MVVM) Event 處理

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-mvvmlightcode

參考上述連接中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://social.technet.microsoft.com/wiki/contents/articles/18199.event-handling-in-an-mvvm-wpf-application.aspx

http://www.codeproject.com/Articles/274982/Commands-in-MVVM#example9

相關文章
相關標籤/搜索