DataGrid中实现标题栏和内容居中

内容居中风格

<Style
    x:Key="HorizontalAlignedData"
    BasedOn="{StaticResource {x:Type TextBlock}}"
    TargetType="{x:Type TextBlock}">
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="VerticalAlignment" Value="Center" />
</Style>

标题居中风格

<Style TargetType="DataGridColumnHeader">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="BorderBrush" Value="#a8a8a8" />
    <Setter Property="Background" Value="#f2f2f2" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="Padding" Value="5" />
    <Setter Property="Foreground" Value="{StaticResource TextColorGeneral}" />
    <Setter Property="BorderThickness" Value="0,0,1,1" />
</Style>

实现各列按比例显示

将列宽设置为星即可 width="*"


<DataGridTextColumn
    Width="*"
    Binding="{Binding Name}"
    ElementStyle="{StaticResource HorizontalAlignedData}"
    Header="项目"
    IsReadOnly="True" />

完整demo代码


<DataGrid.Columns>

    <DataGridTextColumn
        Width="*"
        Binding="{Binding Name}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="项目"
        IsReadOnly="True" />

    <DataGridTextColumn
        Width="*"
        Binding="{Binding Value}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="结果"
        IsReadOnly="True" />

    <DataGridTextColumn
        Width="2*"
        Binding="{Binding Tolerance}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="公差"
        IsReadOnly="True" />

</DataGrid.Columns>


posted @   潜谷先生  阅读(881)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示