How to set the DataContext on a DataGrid Column Header

纵然是瞬间 提交于 2019-11-29 00:09:19

Turns out that one can use the Header property (which is of type Object) as the DataContext for the DataTemplate (set as shown above):

Style headerStyle = (Style)Resources["ColumnHeaderStyle"];
DataGridTextColumn col = new DataGridTextColumn();
col.HeaderStyle = headerStyle;
col.Header = myHeaderDataContext; // DataContext for ColumnHeaderStyle
dataGrid.Columns.Add(col);

Here's how you would do it in XAML (this works in WPF; not sure if it works in SL)

<DataGridTextColumn Binding="{Binding Path=Discount}">
    <DataGridTextColumn.HeaderStyle>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="Content" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.DiscountHeader}" />
        </Style>
    </DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>

Based on Matt's answer, I came up with the solution of binding the header on the DataGridCellsPanel which in Snoop appeared to have the correct data context :

  <DataGridTemplateColumn.HeaderStyle>
     <Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource CenterAlignedColumnHeaderStyle}">
         <Setter Property="Content" Value="{Binding Path=DataContext.Location, RelativeSource={RelativeSource AncestorType={x:Type DataGridCellsPanel}}}" />
      </Style>
  </DataGridTemplateColumn.HeaderStyle>

And this is non intrusive in the way that you can still inherits from custom styled headers (see exemple above) or event the base column header style:

 <DataGridTemplateColumn.HeaderStyle>
     <Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
     <Setter Property="Content" Value="{Binding Path=DataContext.Location, RelativeSource={RelativeSource AncestorType={x:Type DataGridCellsPanel}}}" />
     </Style>
 </DataGridTemplateColumn.HeaderStyle>

This solution has the advantage of being pure and clean XAML and to refer to the closest ancestor holding the correct datacontext rather than trying to reach datacontext of top hierarchy elements like UserControl.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!