WPF DataGrid - how to set the column headers to ha

2019-02-19 18:27发布

Well, actually rotated -90 degrees from horizontal is what I mean. I need to do this because the text for the header is quite long but the cell value is short, and I want to fit a lot of columns on the screen. Is it possible to do this easily or do I need to learn about resources and templates first? I don't mind a "hack" solution!

2条回答
小情绪 Triste *
2楼-- · 2019-02-19 19:00

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.

查看更多
小情绪 Triste *
3楼-- · 2019-02-19 19:01

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.

查看更多
登录 后发表回答