How to set vertical text in the column headers of WPF DataGrid?

瘦欲@ 提交于 2019-11-28 12:58:16

This will rotate the whole ColumnHeaderCell:

<DataGrid.ColumnHeaderStyle>
    <Style TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="LayoutTransform">
            <Setter.Value>
                <RotateTransform Angle="270" />
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.ColumnHeaderStyle>

Be aware: this means HorizontalContentAlignment is then a VerticalContentAlignment and vice versa.

Here is another way to do it:

    <Style x:Key="soDataGrid_ColumnHeaderRotateStyle" TargetType="DataGridColumnHeader" >
    <Setter Property="ContentTemplate" >
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{Binding}"
                           FontWeight="Bold" Width="60"
                           VerticalAlignment="Center" TextAlignment="Center"
                           HorizontalAlignment="Center">
                    <TextBlock.LayoutTransform>
                        <RotateTransform Angle="270" />
                    </TextBlock.LayoutTransform>
                </TextBlock>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>

You can use the style as follows

<DataGridComboBoxColumn Header="Portrait / &#x0a;Landscape" Width="42"
     HeaderStyle="{StaticResource soDataGrid_ColumnHeaderRotateStyle}"
     SelectedItemBinding="{Binding Orientation}"  
     ItemsSource="{Binding Mode=OneWay, 
     Source={StaticResource languageEnum}}" />

I find this approach gives you a lot of control. It is helpful to use the line break code in long header text.

Unfortunately I have found you need to hardcode the width of the rotated textblock - maybe there is a better way to set this width based on the text content.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!