WPF Interactivity 事件(轉)


WPF中不是所有的控件都有Command屬性的,如果窗體我需要在ViewModel中處理Loaded事件命令,或者其他事件的命令時,很難都過綁定Command完成,必須要注冊依賴屬性或事件等,太麻煩了。我喜歡簡約、有效的方式,現在我和大家一起分享一下。

場景,我需要處理Button的Click和MouseMove事件,但又避免用后置代碼,盡量要在ViewModel中獲取。單獨一個Click可以通過Button的Command來完成,在前兩篇文章中我已介紹過,現在就來處理MouseMove事件,這是需要一個System.Windows.Interactivity.dll,該dll是安裝Blend后才有的,在C:\Program Files\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries目錄中,然后我們仍需要Prism.dll。

xaml:

<Window x:Class="WpfApplication1.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:vm="clr-namespace:WpfApplication1"
Title="Window2" Height="124" Width="214">
<Window.DataContext>
<vm:Window2ViewModel />
</Window.DataContext>
<Grid>
<Button Name="btn" Content="Button" Height="33" HorizontalAlignment="Left" Margin="40,24,0,0" VerticalAlignment="Top" Width="109">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding Command1}" CommandParameter="10" />
</i:EventTrigger>
<i:EventTrigger EventName="MouseMove">
<i:InvokeCommandAction Command="{Binding Command2}" CommandParameter="{Binding ElementName=btn}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</Window>

注意;xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"就是導入Blend的dll,然后在控件內部用<i:Interaction.Triggers/>即可,其它應該一看就知道,我通過事件觸發器,來引發ViewModel中兩個Command,第二個Command的參數是Button對象,通過ElementName=btn來指定。

ViewModel:

namespace WpfApplication1 {
public class Window2ViewModel {

public ICommand Command1 {
get {
return new DelegateCommand<string>((str) => {
MessageBox.Show("Command1 with parameter:"+str);
});
}
}

public ICommand Command2 {
get {
return new DelegateCommand<Button>((button) => {
Point p = Mouse.GetPosition(button);
button.Content = string.Format("{0},{1}", p.X, p.Y);
});
}
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM