In WPF, how can I limit a selection in a DataGrid to only cells in a single row or column?

We have a DataGrid that allows the user to select cells multiple times. However, we have a unique business requirement. In particular...

  • First cell: you can choose anywhere
  • Second cell: must be either in the same row or in the same column as the first cell.
  • Additional cells: must be in the same row or column as defined by the second cell.

I don’t see any PreviewSelectionChanges methods and I don’t see any way to block Shift-Selection that cross the boundaries of a valid selection.

My current thought is to maintain the properties int? Row;and int? Col;which I use to crop selected cells after I receive the event with the changed selection, but it seems to me that this is not so clear, since this happens after the fact. I need something that says: "Cell (c, r) is about to become selected. Will you allow it and I can go from there.

So ... Thoughts?

+3
source share
2 answers

, , - MouseDown. , MouseDown , MouseUp, . , , MouseDown "" , , .

MouseClick ( , ), , "" . , , . , DataGrid ( ), .

0

, SelectedCellsChanged . " ", , , , , , .

:

void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) {
   DataGrid dg = (DataGrid)sender;

   var first_cell = dg.SelectedCells.FirstOrDefault();
   if (first_cell != null) {
      var ok_col = first_cell.Column;
      var to_remove = dg.SelectedCells.Where(c => c.Column != ok_col).ToList();
      foreach (var c in to_remove) dg.SelectedCells.Remove(c);
   }
}
0

All Articles