Freigeben über


Rotate your text in the WPF DataGrid column headers

I was talking to Cheryl who writes for the Silverlight User Education team and she was trying to make DataGrid column headers with angled text. She was having trouble getting it to work so we sat down to look at it. We couldn't make it work, but I went back to my office and started working on it in WPF.  Before long, I'd come up with a solution. However, since it was trickier than I thought it would be, I'm sharing it here. (By the way, I'm using .NET Framework 4 Beta 2 but you can get the DataGrid from the WPF toolkit too.)

To get angled text in the column header (as opposed to actually angling the column headers themselves which is a different problem and one I may have to try next now that I've thought of it), you want to update the DataTemplate for the content in the header. So, first I created a DataTemplate to hold the text. You need to apply the transform before the layout pass otherwise your header will get a layout slot with a size to hold the text horizontally, then the rotation is applied and your text gets clipped. LayoutTransform is a property on FrameworkElement which does exactly what I wanted. Here is my DataTemplate:

 <DataTemplate x:Key="RotateHeaderTemplate" >  

                <TextBlock Text="{Binding}" Foreground="Blue" >

                    <TextBlock.LayoutTransform>

                        <RotateTransform Angle="-35" />

                    </TextBlock.LayoutTransform>

                </TextBlock>

        </DataTemplate>

Then I needed to apply this to all the header templates. This was what took me a while to figure out.  I was trying to find something like ColumnHeaderDataTemplate but that didn't exist.  There is a HeaderTemplate property on the DataGridColumn class but I couldn't use that since its an abstract class. You can apply the template to each column individually which I tried, but I really wanted to use a Setter in a Style. Finally, I figured out that I could apply the style to DataGridColumnHeader which inherits from ContentControl and therefore has a ContentTemplate. The ContentTemplate is the DataTemplate for the ContentControl. Exactly what I needed.Here is the Style.

<Style TargetType="DataGridColumnHeader">

<Setter Property="ContentTemplate" Value="{StaticResource RotateHeaderTemplate}" />

       </Style>

And that's it. Now all of my headers are angled. Here's what it looks like.

DataGridRotateHeader

 

Don’t forget to check the MSDN documentation if you have other DataGrid questions. For the solution in a Silverlight application, see Using the Silverlight Toolkit LayoutTransformer Control for Angled Column Header Text.

Margaret