【问题标题】:Set DataGridTextColumn.ElementStyle by background code通过后台代码设置 DataGridTextColumn.ElementStyle
【发布时间】:2012-08-23 10:23:04
【问题描述】:

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

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

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

我可以通过 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>

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

我能做什么?

【问题讨论】:

    标签: c# wpf xaml datagrid


    【解决方案1】:

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

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

    【讨论】:

    • 当我运行它时,我在显示 UI 之前收到错误“TextBlock”TargetType 与元素“DataGridCell”的类型不匹配。我错过了吗?
    • @ErnodeWeerd 是的,您是对的,这是为了在编辑中更改最少 6 个字符。但是 Typeof 不起作用。使用没有大写的 typeof。但除此之外它工作正常!
    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多