【发布时间】:2019-12-23 18:12:54
【问题描述】:
上下文
我在 WPF MVVM 应用程序中有一个 DataGrid,其中包含来自绑定集合的多行。集合中的每个对象都具有不同类型的属性,例如Name 是一个字符串,InsertDate 是一个 DateTime 等等。
由于各种原因,DataGrid SelectionUnit 需要设置为“Cell”。
问题
我正在设置一个链接到一个命令的键绑定,该命令会将当前选定的单元格设置为上一行中相同单元格的值。 (我已经处理了没有前一行的情况)。
我的尝试
我成功地将整个 DataGrid 作为 CommandParameter 传递给命令:
<KeyBinding Command="{Binding RepeatFieldAboveCommand}"
CommandParameter="{Binding ., ElementName=identitiesGrid}"
Key="F5" />
...然后在命令中...
public override void Execute(object parameter)
{
var dataGrid = parameter as DataGrid;
}
然后我可以访问绑定到当前行和前一行的对象
Identity currentRow = dataGrid.CurrentItem as Identity;
int currentRowIndex = dataGrid.Items.IndexOf(dataGrid.CurrentItem);
Identity previousRow = dataGrid.Items[currentRowIndex - 1] as Identity;
我也可以用
获取选中列的索引int displayIndex = dataGrid.CurrentColumn.DisplayIndex;
但我找不到直接引用单元格值以进行复制的方法。我考虑过通过 CommandParameter 传递一些更有用的东西,但我想不出是什么。
【问题讨论】: