【问题标题】:Change the Background Color of Entire Column of WPF DataGrid at RunTime在运行时更改 WPF DataGrid 整列的背景颜色
【发布时间】:2013-03-16 15:55:43
【问题描述】:

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

  1. Change WPF Datagrid Row Color

  2. How do I programatically change datagrid row color in WPF?

  3. Programmatically assigning a color to a row in DataGrid

  4. Change DataGrid cell colour based on values

等。

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

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

感谢您的宝贵时间。

【问题讨论】:

    标签: c# wpf datagrid colors


    【解决方案1】:

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

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

    希望对你有帮助。

    【讨论】:

    • 感谢您的宝贵时间,但我想知道如何在运行时执行此操作,因为我拥有的列是可变的并且是在运行时创建的。万事如意...
    • 我希望它在运行时完成。我正在将数据网格与窗口加载上的数据表绑定。那么怎么做呢?
    • 我做了你在回答中指出的事情,它奏效了。但是如何在运行时以编程方式更改它?
    【解决方案2】:

    有点旧,但您可以通过以下方式以编程方式执行此操作(对于 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 列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 2020-06-02
      相关资源
      最近更新 更多