首页 > 解决方案 > It's possible to convert event triggers to viewmodel using converters?

问题描述

I'm writing WPF app in MVVM using MVVM Light. I have an event trigger in DataGrid to detecting the cell editing ends.

In viewmodel I have command which needs a DataGrid binding item as param. I did it using casting DataGridCellEditEndingEventArgs.EditingElement.DataContext to my model. It's work as I want but it's hard to VM testing.

Here's View's trigger

// xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<DataGrid x:Name="PeopleDataGrid" ItemsSource="{Binding People}" >
<i:Interaction.Triggers>
                            <i:EventTrigger EventName="CellEditEnding">
                                <cmd:EventToCommand PassEventArgsToCommand="True" Command="{Binding EditPersonRowCommand}"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>

And in VM here's the command

public RelayCommand<DataGridCellEditEndingEventArgs> EditPersonRowCommand
        {
            get
            {
                return editPersonRowCommand ??
                       (editPersonRowCommand =
                           new RelayCommand<DataGridCellEditEndingEventArgs>(param => this.EditPersonRow(param.EditingElement.DataContext as PersonForListDto), this.editPersonRowCommandCanExecute));
            }
        }

It's possible to using IValueConverter or something to have model right way without control casting?

标签: c#.netwpfmvvmmvvm-light

解决方案


依赖属性将PassEventArgsToCommand事件参数传递给命令。PassEventArgsToCommand您可以定义绑定CommandParameter来传递 DataContext ,而不是使用。有了这个,在VM,RelayCommand可以用实际类型定义。View 和 ViewModel 的代码如下:

<i:Interaction.Triggers>
                            <i:EventTrigger EventName="CellEditEnding">
                                <cmd:EventToCommand Command="{Binding EditPersonRowCommand}" CommandParameter="{Binding //Since you have not given the full code so not sure how Binding is cascading so if you require to use ReleativeSource to bind to DataContext then use that.}"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>

public RelayCommand<PersonForListDto> EditPersonRowCommand
        {
            get
            {
                return editPersonRowCommand ??
                       (editPersonRowCommand =
                           new RelayCommand<PersonForListDto>(param => this.EditPersonRow(param), this.editPersonRowCommandCanExecute));
            }
        }

有了上面,你的虚拟机会更干净,可以很容易地进行单元测试。


推荐阅读