c# - 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?
解决方案
依赖属性将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));
}
}
有了上面,你的虚拟机会更干净,可以很容易地进行单元测试。
推荐阅读
- javascript - 我可以使用 pactjs 测试通过事件流和消息队列进行通信的微服务吗?
- python - 从 pandas datafrmae 开始有条件地删除行
- sql - 内连接 SQL 与 like 运算符
- javascript - Draft-js 保存和显示 HTML
- xml - 错误:'不支持的 XSL 元素'http://www.w3.org/1999/XSL/Transform:for-each-group''
- jquery - 在 jVectorMap 中设置标记图像的宽度/高度
- scala - Spark中的rdd.map函数可以在特定条件下没有返回吗?
- php - 自定义 404 显示 php 文件的“找不到文件”而不是重定向
- linear-programming - Gurobi ILP:添加新约束后的解决方案起点
- macros - AHK 模拟按住键同时物理按住键