How to stretch WPF DataGridColumn's header when create?

1.9k views Asked by At

I generate my columns dynamicaly and would like to stretch their headers, like here

enter image description here

In generall the columns can have different names so it is not possible to set a fixed MinWidth. Is it possible through changing the DataGrid.ColumnHeaderStyle to set somehing like horizontal margin for the header text? Here is my XAML:

<DataGrid x:Name="ResultDataGrid" Margin="2"
    ItemsSource="{Binding MyData, Mode=OneWay}"
    DisplayMemberPath="Persons"
    SelectedItem="{Binding SelectedPerson}"
    GridLinesVisibility="None" 
    AutoGenerateColumns="False" 
    CanUserAddRows="False" 
    CanUserDeleteRows="False" 
    CanUserReorderColumns="False"
    IsReadOnly="True"
    SelectionMode="Single"
    AllowDrop="True">
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="Height" Value="25" />
            <Setter Property="FontWeight" Value="Black" />
            <Setter Property="SeparatorBrush" Value="LightGray" />
        </Style>
    </DataGrid.ColumnHeaderStyle>
</DataGrid>     
1

There are 1 answers

1
dkozl On BEST ANSWER

You can add another Setter to your Style to change ContentTemplate to TextBlock with left/right margin set

<DataGrid.ColumnHeaderStyle>
   <Style TargetType="{x:Type DataGridColumnHeader}">
      <Setter Property="HorizontalContentAlignment" Value="Center" />
      <Setter Property="Height" Value="25" />
      <Setter Property="FontWeight" Value="Black" />
      <Setter Property="SeparatorBrush" Value="LightGray" />
      <Setter Property="ContentTemplate">
         <Setter.Value>
            <DataTemplate>
               <TextBlock Text="{Binding}" Margin="20,0"/>
            </DataTemplate>
         </Setter.Value>
      </Setter>
   </Style>
</DataGrid.ColumnHeaderStyle>