简体   繁体   English

WPF Datagrid - 在DataGrid中单击空格时取消选择所选项

[英]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 默认行为是使用CTRL +单击以取消选择数据网格中的项目

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. 我已经google了它,发现了一些非常复杂的变通方法,但我希望有一个简单的解决方案。

Edit: 编辑:

I'm now using a listview instead, and still havent found a solution. 我现在正在使用listview,但仍未找到解决方案。 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. 唯一的缺点是在所选项目上没有CTRL的单击也会取消选择。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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