Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture "Click" events on a DataGrid column headers

Tags:

.net

wpf

.net-4.0

It appears that the DataGrid that comes with .NET 4 does not contain an event for both column and row header clicks. I want to receive events for the column header click as I want to provide my own sorting behaviour and turn off the default sorting, this is because my view-model is a paginated model that will only display 25/50/100 rows at a time, the default sorting will of-course sort the current page only.

Now I could create a new DataGridColumnHeader style which contains a clickable element and and set ColumnHeaderStyle, though this just seems like a pain as I'll have trouble figuring out things like which column it was that got clicked etc.

Anyone else come up against this and solved it?

like image 632
Brett Ryan Avatar asked May 05 '11 09:05

Brett Ryan


1 Answers

The headers are just buttons. Like any button, you can register to the Click event to capture those clicks. Just set a style targeting DataGridColumnHeader and add a Click event handler. Then within the handler, you have access to the header directly via the sender. You could then get the Column associated with that header and other information associated with it.

<DataGrid>
    <DataGrid.Resources>
        <Style TargetType="DataGridColumnHeader">
            <EventSetter Event="Click" Handler="columnHeader_Click" />
        </Style>
    </DataGrid.Resources>
</DataGrid>

Then in the code:

private void columnHeader_Click(object sender, RoutedEventArgs e)
{
    var columnHeader = sender as DataGridColumnHeader;
    if (columnHeader != null)
    {
        // do stuff
    }
}

Looking further into the DataGrid, I noticed that there's a ColumnHeaderStyle property. I think it would be a better idea to apply the style through this property instead.

<DataGrid>
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="DataGridColumnHeader">
            <EventSetter Event="Click" Handler="columnHeader_Click" />
        </Style>
    </DataGrid.ColumnHeaderStyle>
</DataGrid>
like image 157
Jeff Mercado Avatar answered Sep 22 '22 22:09

Jeff Mercado