【WPF】向command中傳遞EventArgs參數,使用mvvmlight

一般code-behind中的事件有sender和EventArgs兩個參數,而如果採用MVVM的模式,command中只能傳遞一個commandParameter參數。

可以使用EventTrigger,結合MVVMLight提供的EventToCommand,將屬性PassEventArgsToCommand設置爲True,在ViewModel中使用RelayCommand<EventArgs>即可以接收到傳入的EventArgs,使用e.Source屬性就可以獲取原事件中的sender

具體用法如下(其中EventTrigger的用法可以參考之前的文章):

// xaml中的代碼
// xaml頭部添加命名空間
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftButtonDown">
        <cmd:EventToCommand Command="{Binding Canvas_MouseLeftButtonDown}" PassEventArgsToCommand="True"/>
    </i:EventTrigger>
    <i:EventTrigger EventName="MouseLeftButtonUp">
        <cmd:EventToCommand Command="{Binding Canvas_MouseLeftButtonUp}" PassEventArgsToCommand="True"/>
    </i:EventTrigger>
    <i:EventTrigger EventName="MouseMove">
        <cmd:EventToCommand Command="{Binding Canvas_MouseMove}" PassEventArgsToCommand="True"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

// viewModel中的代碼
public ICommand RoiMoveStartCommand => new RelayCommand<MouseButtonEventArgs>(Canvas_MouseLeftButtonDown);

public void Canvas_MouseLeftButtonDown(MouseButtonEventArgs e)
{
    FrameworkElement element = e.Source as FrameworkElement;
    // your code here
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章