WPF Datagrid - unselect selected item when pressing spacebar in DataGrid

The default is CTRL + Click to deselect items in the Datagrid

I want to be able to click (left or right button) a space in the grid and deselect selected elements.

I searched it to death and found some incredibly complex workarounds, but I hope for a simple solution.

Edit:

Now I am using listview and still have not found a solution. This is a little less annoying to the list because they are better styled.

+5
source share
5 answers

I had the same question and found a solution. This should be built in behavior:

private void dataGrid1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (sender != null)
    {
        DataGrid grid = sender as DataGrid;
        if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
        {
            DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
            if (!dgr.IsMouseOver)
            {
                (dgr as DataGridRow).IsSelected = false;
            }
         }
    }        
}
+10
source

Plain

<DataGrid MouseDown="DataGrid_MouseDown">

not what you want?

private void DataGrid_MouseDown(object sender, MouseButtonEventArgs e)
{
    (sender as DataGrid).SelectedItem = null;
}

, CTRL .

+3

, . :

    private void dataViewImages_MouseUp(object sender, MouseEventArgs e)
    {
        DataGridView.HitTestInfo hit = dataViewImages.HitTest(e.X, e.Y);
        if (hit.Type != DataGridViewHitTestType.Cell)
           dataViewImages.ClearSelection();
    }

This is what I use to deselect all cells by clicking in the gray space.

0
source
private void dg_IsKeyboardFocusWithinChanged
    (object sender, DependencyPropertyChangedEventArgs e)
    {
        if (dg.SelectedItem != null) {
            dg.UnselectAll();
        }
    }
0
source

If you have SelectionUnit="FullRow", you should use UnselectAllCells()instead UnselectAll().

0
source

All Articles