LIU
LIU

Reputation: 315

Set DataGridTextColumn.ElementStyle by background code

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.

<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.

What can i do?

Upvotes: 6

Views: 7797

Answers (1)

Emond
Emond

Reputation: 50672

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);
}

Upvotes: 8

Related Questions