Skip to content

Text wrapping in WPF DataGrid column header

April 12, 2011

The WPF DataGrid does not support out of the box wrapping of the text in the column headers. With a small style adjustment it’s possible to wrap the text in the header.

First we create a new style for the DataGridColumnHeader class. In this style we only set the property ContentTemplate so the orginal style is not touched. The ContentTemplate is set to a DataTemplate which contains a TextBlock. The TextWrapping property of this TextBlock is set Wrap. This way we have a column header with the header text wrapped.

<Style x:Key="WrappedColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{Binding}"></TextBlock>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

In the columns of the DataGrid we set the HeaderStyle property to the new style.

<DataGrid ItemsSource="{Binding }" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn HeaderStyle="{StaticResource WrappedColumnHeaderStyle}" Header="Long header text" Width="50" Binding="{Binding Name}"/>
    </DataGrid.Columns>
</DataGrid> 

As you can see in the picture below the header text is wrapped when the text is too long for the column width.

About these ads

From → .NET, DataGrid, WPF

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: