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">
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With