wpfbindingwpfdatagriddatagridtextcolumndatagridcolumnheader

How to get the WPF column binding field from DataGridColumnHeader style


I am doing custom sorting for WPF datagrid (as I use pagination so I can not use default sorting), how can I get name of the field that column binding to? Below is my current code inside DataGrid.Resources

    <Style TargetType="DataGridColumnHeader">
        <Setter Property="Command" Value="{Binding Path=DataContext.SortCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
        <Setter Property="CommandParameter" Value="{Binding Path=DisplayIndex, RelativeSource={RelativeSource Mode=Self}}"/>
    </Style>

I try to get the Column but it return null?


Solution

  • I figured it out, I give the style a key

    <DataGrid.Resources>
        <Style x:Key="SortableColumnHeader" TargetType="DataGridColumnHeader">
            <Setter Property="Command" Value="{Binding Path=DataContext.SortCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
            <Setter Property="CommandParameter" Value="{Binding Path=Column.Binding.Path.Path, RelativeSource={RelativeSource Mode=Self}}"/>
        </Style>
    </DataGrid.Resources>
    

    and apply it in column's HeaderStyle and it worked

    <DataGridTextColumn Binding="{Binding Name}" Header="Column Name" MinWidth="150" HeaderStyle="{StaticResource SortableColumnHeader}"/>