Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

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.

like image 839
NoPyGod Avatar asked May 19 '12 16:05

NoPyGod


2 Answers

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;
            }
         }
    }        
}
like image 172
user2242281 Avatar answered Oct 23 '22 15:10

user2242281


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.

like image 45
LPL Avatar answered Oct 23 '22 15:10

LPL