How can I override DataGrid selection behavior?

前端 未结 3 1792
不思量自难忘°
不思量自难忘° 2021-01-22 06:27

I would like to modify the selection behavior of the DataGrid in the following way. Normally when you have multiple rows selected, and then you click one of the items already se

3条回答
  •  失恋的感觉
    2021-01-22 06:57

    Actually you had a solution: make a styling for DataGridCell and set an event handler, but I suppose there was a logical error in your event handler: you have set e.Handled to true, if DataGridCell was selected, so the inner controls could not be manipulated, because the default behavior for DataGrid is first select/unselect the row/cell(and only then manipulate the inner controls), so in case you have multiple selection the clicked upon row/cell was selected, so actually you only have needed to prevent selection of row/cell clicked upon in case of multiple selection.

    I suppose this should work as you have expected:

    
                
            
    
    
    private void PreviewMouseDown(object sender, MouseButtonEventArgs e)
            {
                var cell = sender as DataGridCell; if (cell == null) { return; }
                DataGrid parGrid = null;
                var visParent = VisualTreeHelper.GetParent(cell);
                while (parGrid==null && visParent != null)
                {
                    parGrid = visParent as DataGrid;
                    visParent = VisualTreeHelper.GetParent(visParent);
                }
                if (parGrid==null) { return; }
    
                e.Handled = cell.IsSelected && Keyboard.Modifiers == ModifierKeys.None && parGrid.SelectedItems.Count > 1;
            }
    

提交回复
热议问题