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

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>

Tags:

.Net

Wpf

.Net 4.0