可以使用转换器将事件触发器转换为视图模型吗?

It's possible to convert event triggers to viewmodel using converters?

我正在使用 MVVM Light 在 MVVM 中编写 WPF 应用程序。我在 DataGrid 中有一个事件触发器来检测单元格编辑结束。

在视图模型中,我有一个命令需要一个 DataGrid 绑定项作为参数。我通过将 DataGridCellEditEndingEventArgs.EditingElement.DataContext 转换为我的模型来做到这一点。效果如我所愿,但很难进行 VM 测试。

这是视图的触发器

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

在 VM 中,这是命令

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

是否可以使用 IValueConverter 或其他东西在没有控制转换的情况下以正确的方式建立模型?

PassEventArgsToCommand 依赖项 属性 将事件参数传递给命令。您可以为 CommandParameter 定义绑定以传递 DataContext,而不是使用 PassEventArgsToCommand。这样,在 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));
            }
        }

有了上面的内容,您的 VM 会更干净并且可以轻松地进行单元测试。