WPF DataGrid top left select all title buttons, does not focus grid

My control is using WPF DataGrid. If you click the blank header in the upper left corner, it selects all rows. This is a standard part of DataGrid, not something I added.

However my users are having problems because this 'button' is not focusing the DataGrid. How can I fix this?

System.Windows.Controls.DataGrid

Edit: This is the Excel analogue of the DataGrid button I'm talking about. This is not a real button, but a title of some kind:

enter image description here

+3


source to share


2 answers


If you look at Snoop , you may notice this button.

enter image description here



So you can write an event handler Click

for that button, and in that handler, you can focus the grid.

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

      

+4


source


I used an alternative that doesn't rely on the visual tree for the control:

In XAML:

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

      



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

      

It also gave me the option to deselect all if all cells were selected.

+2


source







All Articles