【问题标题】:Change the background color of a single DataGrid column header更改单个 DataGrid 列标题的背景颜色
【发布时间】:2017-08-18 00:15:47
【问题描述】:

我正在使用 WPF DataGrid,我想更改单个列标题背景颜色,而不影响其他列。

我发现了以下问题:

How to change column header's background color when using WPF datagrid,

但这会更改所有列标题,我只想更改一个。

【问题讨论】:

    标签: c# wpf xaml wpfdatagrid


    【解决方案1】:

    当你使用类似的东西时:

    <DataGrid>
      <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
          <Setter Property="Background" Value="Blue" />
        </Style>
      </DataGrid.Resources>
    </DataGrid>
    

    您正在为该范围内的所有ColumnHeaders 更改DataGridColumnHeader Style,因为尚未为Style 指定Key

    现在,假设DataGridItemsSourceList&lt;C&gt;,其中C 是一个具有string 属性的类,称为AB。这是你可以做的只设置A列的Style

    <DataGrid>
      <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}"
               Key="SpecialHeaderStyle"> <!-- here I set the Style's Key -->
          <Setter Property="Background" Value="Blue" />
        </Style>
      </DataGrid.Resources>
      <DataGrid.Columns>
        <!-- for this column I set the HeaderStyle property -->
        <DataGridTextColumn Binding="{Binding A}"
                            Header="A"
                            HeaderStyle="{StaticResource SpecialHeaderStyle}"/>
        <!-- for this column I don't -->
        <DataGridTextColumn Binding="{Binding B}"
                            Header="B"/>
      </DataGrid.Columns>
    </DataGrid>
    

    您将只在列A 上设置特殊的Style

    顺便说一句,请注意这一点:如果您以这种方式更改Style,您将设置一个固定的背景颜色,如果您使用鼠标越过该颜色也不会改变。为了使标题 UI 更具响应性,您必须覆盖其整个模板。阅读this 进行更广泛的讨论。

    【讨论】:

    • 我正在使用 materialdesigninxaml 将样式应用于我的 DataGrid 以使其看起来不错。当我使用 HeaderStyle 时,它​​似乎覆盖了 materialdesigninxaml 中的所有样式。有没有办法保留 materialdesignxaml 中的样式并且只应用资源样式的更改?
    • @DavidLee 尝试进入this question。它可能会帮助你(但我不确定)。
    猜你喜欢
    • 2014-04-06
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2017-09-19
    • 2020-06-02
    • 2014-12-12
    相关资源
    最近更新 更多