26

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

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

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

  3. 以编程方式为 DataGrid 中的行分配颜色

  4. 根据值更改 DataGrid 单元格颜色

等。

我已经在MSDN DataGrid 页面CellStyle上看到了该属性,但它的使用对我来说一点也不明显,尽管围绕它进行了搜索。

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

谢谢你的时间。

4

2 回答 2

28

我让它工作的唯一方法是自己设置列(不使用自动生成)。所以首先要做的是定义列:

<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 中声明的静态资源:

<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 操作来操作静态资源。

希望能帮助到你。

于 2013-03-26T22:50:36.623 回答
18

有点老了,但这里是您可以如何以编程方式执行此操作(对于 AutoGen 列):

private void dgvMailingList_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.CellStyle = new Style(typeof(DataGridCell));
    e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty,  new SolidColorBrush(Colors.LightBlue)));
}

同样的方法也可以应用于非 AutoGen 列。

于 2014-02-10T06:21:57.633 回答