wpf 更改 CurrentCellChanged 事件处理程序中的单元格选择不起作用
wpf Change cell selection inside CurrentCellChanged event handler does not work
我有一个 wpf 数据网格,其中 SelectionUnit 设置为 "CellOrRowHeader",SelectionMode 设置为 "Extended"。
<DataGrid SelectionUnit="Cell" SelectionMode="Extended" Name="myDataGrid">
CurrentCellChanged="onCurrentCellChanged"
</DataGrid>
在 onCurrentCellChanged 中,我尝试将选择更改为另一个单元格:
private void onCurrentCellChanged(object sender, EventArgs e)
{
DataGridCell cell = DataGridHelper.GetCell(myDataGrid, 3, 3);
cell.IsSelected = true;
cell.Focus();
}
GetCell 是一个辅助函数。我验证了该单元格不为空,并执行了代码。但是,我只看到单元格 {3,3} 被聚焦(带有黑色边框),但没有突出显示(没有蓝色背景)。
奇怪的是,如果我调用 相同的 代码,但不是在 onCurrentCellChanged 事件回调中,单元格 {3,3} 就会突出显示。
有人知道原因吗?非常感谢!
除了"CurrentCellChanged"之外,还有一个事件"SelectedCellsChanged"表现不同。经过一些测试,我发现这两个事件有不同的用途。例如,在某些情况下,即使选择未更改,也会调用 "CurrentCellChanged"。虽然这超出了这个答案的范围......
回到主题,我设法通过在 SelectedCellsChanged 事件回调中操作单元格选择来解决问题。但是有一些技巧:
更改标记:
<DataGrid SelectionUnit="Cell" SelectionMode="Extended" Name="myDataGrid">
SelectedCellsChanged="onSelectedCellsChanged"
</DataGrid>
这是处理程序:
private void onSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
// trick: Since the code below change the cell selection, which may
// cause this handler to be called recursively, I need to do some filter
// If myDataGrid.CurrentCell != e.AddedCells.First(), return
// Here we can change cell selection
DataGridCell cell = DataGridHelper.GetCell(myDataGrid, 3, 3);
cell.IsSelected = true;
}
我有一个 wpf 数据网格,其中 SelectionUnit 设置为 "CellOrRowHeader",SelectionMode 设置为 "Extended"。
<DataGrid SelectionUnit="Cell" SelectionMode="Extended" Name="myDataGrid">
CurrentCellChanged="onCurrentCellChanged"
</DataGrid>
在 onCurrentCellChanged 中,我尝试将选择更改为另一个单元格:
private void onCurrentCellChanged(object sender, EventArgs e)
{
DataGridCell cell = DataGridHelper.GetCell(myDataGrid, 3, 3);
cell.IsSelected = true;
cell.Focus();
}
GetCell 是一个辅助函数。我验证了该单元格不为空,并执行了代码。但是,我只看到单元格 {3,3} 被聚焦(带有黑色边框),但没有突出显示(没有蓝色背景)。
奇怪的是,如果我调用 相同的 代码,但不是在 onCurrentCellChanged 事件回调中,单元格 {3,3} 就会突出显示。
有人知道原因吗?非常感谢!
除了"CurrentCellChanged"之外,还有一个事件"SelectedCellsChanged"表现不同。经过一些测试,我发现这两个事件有不同的用途。例如,在某些情况下,即使选择未更改,也会调用 "CurrentCellChanged"。虽然这超出了这个答案的范围......
回到主题,我设法通过在 SelectedCellsChanged 事件回调中操作单元格选择来解决问题。但是有一些技巧:
更改标记:
<DataGrid SelectionUnit="Cell" SelectionMode="Extended" Name="myDataGrid">
SelectedCellsChanged="onSelectedCellsChanged"
</DataGrid>
这是处理程序:
private void onSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
// trick: Since the code below change the cell selection, which may
// cause this handler to be called recursively, I need to do some filter
// If myDataGrid.CurrentCell != e.AddedCells.First(), return
// Here we can change cell selection
DataGridCell cell = DataGridHelper.GetCell(myDataGrid, 3, 3);
cell.IsSelected = true;
}