【发布时间】:2011-06-20 07:09:45
【问题描述】:
我已经从 Codeplex 实现了 WPF DataGrid Single-Click Editing。 在该解决方案中,单击的单元格被聚焦并选择行以实现 DataGrid的单击编辑。效果很好。
代码如下:
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
{
if (!cell.IsFocused)
{
cell.Focus();
}
DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
if (dataGrid != null)
{
if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
{
if (!cell.IsSelected)
cell.IsSelected = true;
}
else
{
DataGridRow row = FindVisualParent<DataGridRow>(cell);
if (row != null && !row.IsSelected)
{
row.IsSelected = true;
}
}
}
}
}
但我也希望我的 DataGrid 自动退出编辑模式(不按 Enter 键) 当单元格值更改时。例如,在编辑模式下,我在单元格中有一个组合框。当用户在组合框中选择一个值时,它将自动对所选值进行数据绑定。但是用户仍然需要单击 Enter 退出编辑模式。如何自动退出编辑模式?
我已经尝试监听属性变化并调用 DataGrid 的 CommitEdit 函数来自动退出编辑模式。效果很好,代码如下:
void _gameCompareViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "End Edit")
{
AlignGrid.CommitEdit();
}
}
但现在单击编辑功能不适用于当前单元格。 我必须先单击不同的行才能使其工作。 我想我想要的是当调用 CommmitEdit 时,它会自动选择一个 不同的行。 (就像当你按 Enter 时,它会转到下一行) 有什么建议吗?请告诉我如何执行此操作的代码。我的项目没时间了。
感谢您的帮助。
【问题讨论】:
-
在您以编程方式调用 CommitEdit() 后,
PreviewMouseLeftButtonDown方法中的cell的值是多少?为什么方法无法到达cell.IsSelected = true?