Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a DataGrid to unselect on click when SelectionMode="Extended"?

The default behaviour of a WPF DataGrid is to select when a row is clicked if SelectionMode="Extended" which is what I want, however I also wish for the row to un-select if it was previously already selected when clicked.

I have tried the following which will unselect the row as soon as it's selected, it seems the row selection occurs before the mouse click event.

private void DoGridMouseLeftButtonUp(object sender, MouseButtonEventArgs args) {
    // Get source row.
    DependencyObject source = (DependencyObject)args.OriginalSource;
    var row = source.FindParent<DataGridRow>();
    if (row == null)
        return;
    // If selected, unselect.
    if (row.IsSelected) {
        row.IsSelected = false;
        args.Handled = true;
    }
}

Where I am binding to this event with the following grid.

<DataGrid SelectionMode="Extended"
          SelectionUnit="FullRow"
          MouseLeftButtonUp="DoGridMouseLeftButtonUp">
like image 341
Brett Ryan Avatar asked Jun 24 '11 08:06

Brett Ryan


1 Answers

I have managed to solve this by instead of handling events on the grid itself to handle them on the cell instead, this involves an event setter for DataGridCell as follows:

<DataGrid SelectionMode="Extended"
          SelectionUnit="FullRow">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <EventSetter Event="PreviewMouseLeftButtonDown"
                         Handler="DoCheckRow"/>
        </Style>
    </DataGrid.Resources>
    <!-- Column mapping omitted. -->
</DataGrid>

Event handler code.

public void DoCheckRow(object sender, MouseButtonEventArgs e) {
    DataGridCell cell = sender as DataGridCell;
    if (cell != null && !cell.IsEditing) {
        DataGridRow row = FindVisualParent<DataGridRow>(cell);
        if (row != null) {
            row.IsSelected = !row.IsSelected;
            e.Handled = true;
        }
    }
}

My grid is read only so any edit behavior is ignored here.

like image 60
Brett Ryan Avatar answered Oct 05 '22 12:10

Brett Ryan