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

问题描述 投票:0回答:1

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

在viewmodel中,我有一条命令需要将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或某种无需控制强制转换就可以正确建模的方法?

c# .net wpf mvvm mvvm-light
1个回答
1
投票

PassEventArgsToCommand依赖项属性将事件参数传递给命令。可以使用PassEventArgsToCommand定义绑定以传递DataContext,而不使用CommandParameter。这样,在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将会更干净,并且可以轻松地进行单元测试。

© www.soinside.com 2019 - 2024. All rights reserved.