(WPF, MVVM) Event 處理

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   for   

WPF的有些UI元素有Command屬性可以直接實現綁定,如Button

但是很多Event的觸發如何綁定到ViewModel中的Command呢?

答案就是使用EventTrigger可以實現。

繼續上一篇對Slider的研究,在View中修改Interaction.

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

(參考:http://stackoverflow.com/questions/14331272/issue-with-thumb-dragstarted-event-with-mvvmlight)

參考上述連結中Tom Allen的方法後可以實現, 但是這個方法並沒有很好的遵守MVVM模式。

於是接著研究,既然DragCompleted是掛在Thumb上面的,那麼為何不直接和Thumb 綁定呢?

 

修改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>

 

 

 

 

 

參考:

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.