Search code examples
wpfdatagridwpfdatagriddatagridcolumnheader

Style each datagrid column header


I want to add another row to the HeaderRow and for each column insert specific control.
This is my code where add this row, but I can only set same control (in this case textbox) for every column, but I want to set specific control for specific column. (like it's done in ASP.NET repeater)

<Style x:Key="DataGridColumnHeaderStyle1" TargetType="{x:Type DataGridColumnHeader}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
           <Grid x:Name="grid" VerticalAlignment="Center" HorizontalAlignment="Stretch"  Background="{TemplateBinding Background}">
              <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
              </Grid.RowDefinitions>
              <TextBlock Name="ColumnHeader" Grid.Row="0" Text="{TemplateBinding Content}"  HorizontalAlignment="Center" VerticalAlignment="Center" Height="18" />
              <Grid Grid.Row="1">
                 <TextBox Text="" HorizontalAlignment="Stretch" BorderThickness="0,1,1,1" />
              </Grid>
          </Grid>
</Style>

Solution

  • I approached this a little bit different, I styled DataGridColumnHeadersPresenter, it allows me to syle the column headers row (instead of column header).
    There I add my new row and all the controls I need, I alsoe set the width of every cell to match the width of it's header .

    <Style x:Key="DataGridColumnHeadersPresenterStyle1" TargetType="{x:Type DataGridColumnHeadersPresenter}">
        <Setter Property="Template">
          <Setter.Value>
              <ControlTemplate TargetType="{x:Type DataGridColumnHeadersPresenter}">
                  <Grid>
                    <Grid.RowDefinitions>
                      <RowDefinition Height="*"/>
                      <RowDefinition Height="*"/>                   
                  </Grid.RowDefinitions>
                  <DataGridColumnHeader x:Name="PART_FillerColumnHeader" IsHitTestVisible="False"/>                         
                  <ItemsPresenter/>
                  <Grid  Grid.Row="1" VerticalAlignment="Top" HorizontalAlignment="Left" >
    
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="{Binding ActualWidth, ElementName=Col1}"/>         
                        <ColumnDefinition Width="{Binding ActualWidth, ElementName=Col2}"/>
                        <ColumnDefinition Width="{Binding ActualWidth, ElementName=Col3}"/>
                    </Grid.ColumnDefinitions>
                    <TextBox  Grid.Column="0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Bottom" Width="Auto" Height="25" BorderThickness="1,2,0,2"/>
                       my other controls go here
                  </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
     </Setter>