在运行时更改 WPF DataGrid 整个列的背景颜色 [英] Change the Background Color of Entire Column of WPF DataGrid at RunTime

查看:35
本文介绍了在运行时更改 WPF DataGrid 整个列的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有,我对 WPF 比较陌生.我已经四处寻找答案,但我发现的只是如何在运行时对行进行着色而不是对列进行着色;例如以下问题:

All, I am relatively new to WPF. I have searched around for the answer to this, but all I have found is how to do colorise rows at run-time not columns; for example the following questions:

  1. 更改 WPF 数据网格行颜色

我如何以编程方式更改数据网格WPF中的行颜色?

以编程方式为DataGrid 中的行

根据值更改 DataGrid 单元格颜色

等.

我在 CellStyle 属性="noreferrer">MSDN DataGrid 页面 但它的使用对我来说根本不明显,尽管也搜索了这个.

I have seen the CellStyle property on the MSDN DataGrid pages but its use is not obvious to me at all despite searches around this as well.

如何在运行时更改整列的背景颜色?

感谢您的时间.

推荐答案

我让它起作用的唯一方法是自己设置列(不使用 AutoGenerate).所以首先要做的是定义列:

The only way I got it to work is by setting the columns by myself, (by not using AutoGenerate). So first thing to do is define the columns:

<DataGrid x:Name="Frid" ItemsSource="{Binding Path=.}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="First Name" 
                                Binding="{Binding Path=FirstName}">

            </DataGridTextColumn>

            <DataGridTextColumn Header="Last Name" 
                                Binding="{Binding Path=LastName}">

            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid> 

然后你需要设置每一列的 CellStyle 并将 Background 绑定到一个你可以在 Window.Resources 声明的静态资源:

Then you need to set each column CellStyle and bind the Background to a static resource that you can declare at Window.Resources:

<Window x:Class="WpfApplication1.MainWindow" ...>
<Window.Resources>
    <SolidColorBrush x:Key="clBr" Color="White" />
</Window.Resources>
...

列:

                <DataGridTextColumn Header="First Name" 
                                    Binding="{Binding Path=FirstName}">
                <DataGridTextColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="Background" 
                                Value="{StaticResource clBr}" />
                    </Style>
                </DataGridTextColumn.CellStyle>
            </DataGridTextColumn>

然后您可以通过代码或 xaml 操作来操作静态资源.

then you can just manipulate the static resource by either code or xaml manipulation.

希望有帮助.

这篇关于在运行时更改 WPF DataGrid 整个列的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆