简体   繁体   中英

WPF Datagrid - deselect selected item(s) when clicking whitespace in the DataGrid

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

I want to be able to mouse click (left or right button) the whitespace in the grid and have it deselect any selected items.

I've googled it to death and found some incredibly complex workarounds, but i'm hoping for a simple solution.

Edit:

I'm now using a listview instead, and still havent found a solution. It's slightly less annoying with a listview though because they are styled better.

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

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;
            }
         }
    }        
}

A simple

<DataGrid MouseDown="DataGrid_MouseDown">

is not what you want?

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

The only disadvantage is that a click without CTRL on a selected item deselects all too.

I am not sure whether you mean white space or gray space. In the latter case the following does the job:

    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.

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

如果你有SelectionUnit="FullRow"你必须使用UnselectAllCells()而不是UnselectAll()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM