Bubo Bubo - 25 days ago 6
C# Question

How to get a DataGrid column name when the header is clicked, WPF

I am trying to determine the column name of a clicked column using the following event handler.

Here is the XAML:

<DataGrid Name ="LoggedGrid" HorizontalAlignment="Left" Margin="-3,288,0,0" VerticalAlignment="Top" Height="198" Width="973">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<EventSetter Event="Click" Handler="columnHeader_Click" />
</Style>
</DataGrid.ColumnHeaderStyle>
</DataGrid>


And here is the event handler, I cannot figure out how to determine the column name after the column has been clicked, any ideas?

private void columnHeader_Click(object sender, RoutedEventArgs e)
{

}

Answer

Why not cast the sender as DataGridColumnHeader and then gets its Content like this.

private void columnHeader_Click(object sender, RoutedEventArgs e)
{
    string header = ((DataGridColumnHeader)sender).Content.ToString();
}