在WPF中使用Interaction.Triggers
Interaction Class - static class that owns the Triggers and Behaviors attached properties. Handles propagation of AssociatedObject change notifications (MSDN).
當(dāng)不足以使用ICommand的時候,這種特殊的手段對MVVM模式非常有用。
我們需要在我們的項目中添加兩個引用:
- Microsoft.Expression.Interactions.dll
- System.Windows.Interactivity.dll
代碼例子:
- 1)引用Microsoft.Expression.Interactions.dll和System.Windows.Interactivity.dll
在UserControl添加兩個特性
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" <!--或者--> xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
- 2) 在ViewModel中創(chuàng)建public方法
public void SubmitClicked()
{
MessageBox.Show("Button was clicked");
}- 3) 在UserControl中添加button到Xaml
<Button Content="Submit Method" Width="180">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction TargetObject="{Binding}" MethodName="SubmitClicked"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>如果我們想在這個方法中使用參數(shù),我們應(yīng)該在ViewModel中使用屬性(例如雙向綁定)。
附錄:使用ICommand的例子。
//區(qū)別:這樣可以傳參數(shù),但是綁定的是實現(xiàn)了ICommand接口的類的對象。
//步驟1:引用System.Windows.Interactivity.dll,添加特性。
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
//步驟2:使用?!?
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding ClockWindowLoadCommand}" CommandParameter="{Binding ElementName=txtCardNo}"/>
</i:EventTrigger>
<i:EventTrigger EventName="KeyUp">
<i:InvokeCommandAction Command="{Binding WindowKeyCommand}"/>
</i:EventTrigger>
<i:EventTrigger EventName="Activated">
<i:InvokeCommandAction Command="{Binding WindowActivatedCommand}" CommandParameter="{Binding ElementName=txtCardNo}"/>
</i:EventTrigger>
</i:Interaction.Triggers>到此這篇關(guān)于在WPF中使用Interaction.Triggers的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#數(shù)據(jù)結(jié)構(gòu)與算法揭秘二 線性結(jié)構(gòu)
本文中,我們討論了什么是線性結(jié)構(gòu),線性結(jié)構(gòu)有哪些特點,并且詳細(xì)介紹了一個最簡單線性結(jié)構(gòu)順序表,并且通過源代碼對她進(jìn)行一些列的分析,最后還舉了兩個例子,讓我們更好的理解順序表2012-11-11
C#中foreach循環(huán)對比for循環(huán)的優(yōu)勢和劣勢
循環(huán)語句是編程的基本語句,在C#中除了沿用C語言的循環(huán)語句外,還提供了foreach語句來實現(xiàn)循環(huán),下面這篇文章主要給大家介紹了關(guān)于C#中foreach循環(huán)對比for循環(huán)的優(yōu)勢和劣勢,需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09
Unity實現(xiàn)鼠標(biāo)點2D轉(zhuǎn)3D進(jìn)行旋轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了Unity實現(xiàn)鼠標(biāo)點2D轉(zhuǎn)3D進(jìn)行旋轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-04-04
C#中winform控制textbox輸入只能為數(shù)字的方法
這篇文章主要介紹了C#中winform控制textbox輸入只能為數(shù)字的方法,包括使用keyPress事件限制鍵盤輸入以及TextChanged事件限制粘貼等情況,來實現(xiàn)控制輸入為數(shù)字的功能,需要的朋友可以參考下2015-01-01
C#在Windows上調(diào)用7-zip實現(xiàn)壓縮文件
這篇文章主要為大家詳細(xì)介紹了C#如何在Windows上調(diào)用7-zip實現(xiàn)壓縮文件,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以學(xué)習(xí)一下2023-10-10

