【问题标题】:How to set vertical text in the column headers of WPF DataGrid?如何在 WPF DataGrid 的列标题中设置垂直文本?
【发布时间】:2012-04-21 09:23:21
【问题描述】:

嗯,实际上我的意思是从水平方向旋转了 -90 度。

我需要这样做,因为标题的文本很长,但单元格的值很短,我想在屏幕上容纳很多列。

是否可以轻松做到这一点,还是我需要先了解资源和模板?我不介意“破解”解决方案!

【问题讨论】:

    标签: c# wpf wpfdatagrid


    【解决方案1】:

    这将旋转整个 ColumnHeaderCell:

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

    注意:这意味着HorizontalContentAlignmentVerticalContentAlignment,反之亦然。

    【讨论】:

    • 请注意,这种方法会干扰数据网格的列大小调整行为。
    【解决方案2】:

    这是另一种方法:

        <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>
    

    你可以使用如下样式

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

    我发现这种方法为您提供了很多控制权。在长标题文本中使用换行代码很有帮助。

    不幸的是,我发现您需要对旋转文本块的宽度进行硬编码 - 也许有更好的方法可以根据文本内容设置此宽度。

    【讨论】:

    • 这种方法允许按预期调整列大小。 +1。
    猜你喜欢
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2015-12-31
    • 2011-01-31
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    相关资源
    最近更新 更多