简体   繁体   English

WPF DataGrid左上角选择所有标题按钮不对焦网格

[英]WPF DataGrid top left select all header button doesn't focus the grid

My control uses a WPF DataGrid. 我的控件使用WPF DataGrid。 If you click the empty header in the top left it selects all rows. 如果单击左上角的空标题,则会选择所有行。 This is a standard part of DataGrid, not anything I've added. 这是DataGrid的标准部分,而不是我添加的任何内容。

However, my users are having trouble because this 'button' doesn't focus the DataGrid. 但是,我的用户遇到了麻烦,因为这个“按钮”没有聚焦DataGrid。 How can I fix this? 我怎样才能解决这个问题?

System.Windows.Controls.DataGrid System.Windows.Controls.DataGrid

Edit: This is the Excel analogue of the DataGrid button I am talking about. 编辑:这是我正在谈论的DataGrid按钮的Excel模拟。 It's not a true button, but a header of some kind: 它不是一个真正的按钮,而是某种类型的标题:

在此输入图像描述

If you look in Snoop you can notice this button. 如果您查看Snoop,您可以注意到此按钮。

在此输入图像描述

So you can write event handler to Click event for this button and in this handler you can focus the grid. 因此,您可以为此按钮的Click事件编写事件处理程序,在此处理程序中,您可以聚焦网格。

private void myGrid_Loaded(object sender, RoutedEventArgs e)
{
    DataGrid dg = sender as DataGrid;
    Border border = VisualTreeHelper.GetChild(dg, 0) as Border;
    ScrollViewer scrollViewer = VisualTreeHelper.GetChild(border, 0) as ScrollViewer;
    Grid grid = VisualTreeHelper.GetChild(scrollViewer, 0) as Grid;
    Button button = VisualTreeHelper.GetChild(grid, 0) as Button;

    if (button != null && button.Command != null && button.Command == DataGrid.SelectAllCommand)
    {
        button.Click += new RoutedEventHandler(button_Click);
    }         
}

void button_Click(object sender, RoutedEventArgs e)
{     
    myGrid.Focus();           
}

I used an alternative that doesn't rely on the the visual tree for the control: 我使用了一种替代方案,它不依赖于控件的可视化树:

In the XAML: 在XAML中:

<DataGrid.CommandBindings>
<CommandBinding Command="SelectAll" Executed="MyGrid_SelectAll"/></DataGrid.CommandBindings>

In the code: 在代码中:

private void MyGrid_SelectAll(object sender, ExecutedRoutedEventArgs e)
    {
        var myGrid = (DataGrid)sender;
        myGrid.Focus();
        if (myGrid.SelectedCells.Count == myGrid.Columns.Count * myGrid.Items.Count)
        {
            myGrid.SelectedCells.Clear();
        }
        else
        {
            myGrid.SelectAll();
        }

        e.Handled = true;
    }

This also gave me the ability to implement deselect all if all cells are selected. 如果选择了所有单元格,这也使我能够实现取消选择。

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

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