wpf 通过后台代码设置 DataGridTextColumn.ElementStyle

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12089541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:05:04  来源:igfitidea点击:

Set DataGridTextColumn.ElementStyle by background code

c#wpfxamldatagrid

提问by LIU

I have a datagrid in my user interface. A datatable will bind to it. Beacuse of datatable may have different format, so i add column and bind value for grid at code behind. see below:

我的用户界面中有一个数据网格。数据表将绑定到它。因为数据表可能有不同的格式,所以我在后面的代码中为网格添加了列和绑定值。见下文:

for (int iLoop = 0; iLoop < dtGroup.Columns.Count; iLoop++)
{
    DataGridTextColumn dgColumn = new DataGridTextColumn();
    dgColumn.Header = dtGroup.Columns[iLoop].ColumnName;
    dgColumn.Binding = new Binding(dtGroup.Columns[iLoop].ColumnName);


    this.dgGroupMatrix.Columns.Add(dgColumn);
}

What i want is let grid cell`s background color based on value.

我想要的是让网格单元格的背景颜色基于值。

I can do that by XAML.

我可以通过 XAML 做到这一点。

<DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path= operation_name}" Header="operation_name">
        <DataGridTextColumn.ElementStyle>
            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <Trigger Property="Text" Value="V31">
                        <Setter Property="Background" Value="LightGreen"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGridTextColumn.ElementStyle>
    </DataGridTextColumn>
</DataGrid.Columns>

But i can not set up grid's column at XAML, Beacuse of this grid will have different format.

但是我不能在 XAML 中设置网格的列,因为这个网格会有不同的格式。

What can i do?

我能做什么?

回答by Erno

Just do the same thing in code:

只需在代码中做同样的事情:

for (int iLoop = 0; iLoop < dtGroup.Columns.Count; iLoop++)
{
    DataGridTextColumn dgColumn = new DataGridTextColumn();
    dgColumn.Header = dtGroup.Columns[iLoop].ColumnName;
    dgColumn.Binding = new Binding(dtGroup.Columns[iLoop].ColumnName);

    Style columnStyle = new Style(typeof(TextBlock));
    Trigger backgroundColorTrigger = new Trigger();
    backgroundColorTrigger.Property = TextBlock.TextProperty;
    backgroundColorTrigger.Value = "V31";
    backgroundColorTrigger.Setters.Add(
        new Setter(
            TextBlock.BackgroundProperty,
            new SolidColorBrush(Colors.LightGreen)));
    columnStyle.Triggers.Add(backgroundColorTrigger);
    dgColumn.ElementStyle = columnStyle;

    this.dgGroupMatrix.Columns.Add(dgColumn);
}