如何在创建时拉伸WPF DataGridColumn的标题?

时间:2014-11-12 12:39:53

标签: c# wpf xaml wpfdatagrid datagridcolumnheader

我动态生成我的列,并希望扩展其标题,例如

enter image description here

通常,列可以具有不同的名称,因此无法设置固定的MinWidth。是否可以通过更改DataGrid.ColumnHeaderStyle来设置像标题文本的水平边距一样?这是我的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 个答案:

答案 0 :(得分:0)

您可以向Setter添加另一个Style,使用左/右边距设置将ContentTemplate更改为TextBlock

<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>