Home > OS >  C# WPF DataGrid Column Header fitting TextBox into width
C# WPF DataGrid Column Header fitting TextBox into width

Time:09-16

I've a DataGrid in my C# WPF application and styled the Columns Header with a Label/TextBlock and a TextBox as an instant filter beneath of it.

My target is to fit the width of the TextBox into the width of the DataGridColumn, but I didn't found an acceptable way for me.

Currently I'm using a Viewbox, but this crashes all size measurements of the elements in the header.

Here is an example what it looks like with the Viewbox: enter image description here

As you can see, I've either a too big TextBox and FontSize or a too small TextBox.

My currently code looks like that:

<DataGridTemplateColumn.Header>
<Viewbox StretchDirection="DownOnly">
    <StackPanel>
        <TextBlock Text="Mitarbeiter"/>
        <TextBox x:Name="txtInstantSearchPersonio" HorizontalAlignment="Stretch" TextChanged="evh_InstantFilterChanged"/>
    </StackPanel>
</Viewbox>

</DataGridTemplateColumn.Header>

Is there a way to fit the TextBox into full wifth of the column but don't stretch the height or fontsize?

CodePudding user response:

You could use a Style for DataGridColumnHeader to fit the Textbox inside of a column

   <DataGridTemplateColumn Width="200">
    <DataGridTemplateColumn.HeaderStyle>
      <Style TargetType="{x:Type DataGridColumnHeader}">
          <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
      </Style>
   </DataGridTemplateColumn.HeaderStyle>
   <DataGridTemplateColumn.Header>                        
      <StackPanel>
         <TextBlock Text="Mitarbeiter"/>
         <TextBox x:Name="txtInstantSearchPersonio" HorizontalAlignment="Stretch" TextChanged="evh_InstantFilterChanged"/>
      </StackPanel>                        
   </DataGridTemplateColumn.Header>

CodePudding user response:

Tried by desperation results in an really simple solution.

I put both elements into a StackPanel:

<DataGridTemplateColumn.Header>
<StackPanel>
    <TextBlock Margin="0" Padding="0" Text="Mitarbeiter"/>
    <TextBox HorizontalAlignment="Stretch" TextChanged="evh_InstantFilterChanged"/>
</StackPanel>

</DataGridTemplateColumn.Header>

and set the DataGrid.ColumnHeaderStyle simply to this:

<Style x:Key="style_DataGridColumnHeader" TargetType="DataGridColumnHeader">
    <Style.Setters>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    </Style.Setters>
</Style>

Works fine for me, the TextBox has always full width of the column header.

  • Related