1
votes

I have a wpf datagrid with SelectionUnit set to "CellOrRowHeader" and SelectionMode set to "Extended".

<DataGrid SelectionUnit="Cell"  SelectionMode="Extended" Name="myDataGrid">
    CurrentCellChanged="onCurrentCellChanged" 
</DataGrid>

Inside the onCurrentCellChanged I tried to change the selection to another cell:

private void onCurrentCellChanged(object sender, EventArgs e)
{
    DataGridCell cell = DataGridHelper.GetCell(myDataGrid, 3, 3);
    cell.IsSelected = true;
    cell.Focus();
}

The GetCell is a helper function. I verified that the cell is not null, and the codes are executed. However, I only see the cell {3,3} is focused (with a black border), but not highlighted (without blue background).

The strange thing is that if I call the same code, but not inside onCurrentCellChanged event callback, the cell {3,3} got highlighted.

Anybody knows the reason ? Many thanks!

1

1 Answers

0
votes

Besides "CurrentCellChanged", There is another event "SelectedCellsChanged" that acts differently. After some tests, I figured out that these two events serve different purpose. For example, in some cases, the "CurrentCellChanged" gets called even if the selection is not changed. While that's beyond the scope of this answer...

Back to the topic, I managed to resolve the problem by manipulating the cell selection inside SelectedCellsChanged event call back. BUT there is some trick:

Change the markup:

<DataGrid SelectionUnit="Cell"  SelectionMode="Extended" Name="myDataGrid">
    SelectedCellsChanged="onSelectedCellsChanged" 
</DataGrid>

Here is the handler:

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;
}