How can I get a DataGrid to unselect on click when

2020-03-19 02:25发布

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">

2条回答
Emotional °昔
2楼-- · 2020-03-19 02:34

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.

查看更多
▲ chillily
3楼-- · 2020-03-19 02:50

my wpf datagrid requires CTRL+CLICK for both addition and removal of MULTIPLE rows. so its standard behavior ;) but nevertheless, why you dont use the PreviewMouseDown event and then check for leftmousebutton and Ctrl and do your unselect logic and set e.handled=true?

查看更多
登录 后发表回答