【问题标题】:How to change Datagrid row color at runtime in wpf?如何在 wpf 运行时更改 Datagrid 行颜色?
【发布时间】:2012-08-23 13:28:32
【问题描述】:

我正在使用 WPF DataGrid 并通过使用类 RowItem 在运行时添加行

 public class RowItem //Class
 {
     public int Rule_ID { get; set; }
     public string Rule_Desc { get; set; }
     public Int64 Count_Of_Failure { get; set; }
 }    

adding row at run time like :

dgValidateRules.Items.Add(new RowItem() { Rule_ID = ruleID, Rule_Desc = ruleDesc, Count_Of_Failure = ttlHodlings });

使用下面的 Loading Row 事件代码来更改数据网格行的颜色。但它不起作用。

private void dgValidateRules_LoadingRow(object sender, DataGridRowEventArgs e)
{
  for (int i = 1; i < dgValidateRules.Items.Count; i++)
  {
    if (((RowItem)dgValidateRules.Items[i]).Count_Of_Failure == 0)
      e.Row.Foreground = new SolidColorBrush(Colors.Black);
    else
      e.Row.Foreground = new SolidColorBrush(Colors.Red);
  }
}

谁能告诉我解决方案?

【问题讨论】:

  • Wooow 看看你的问题....你希望有人会费心去读那些烂摊子吗?请在发布之前格式化您的问题。
  • 你到底想改变什么。?行的背景颜色或前景色。?请注意,前景色会改变文本颜色。
  • 是的,我只需要更改文本颜色。

标签: c# wpf wpfdatagrid


【解决方案1】:

因为它是行事件,所以它是做它的磨损的地方,在这里你可以放置一个关于行的条件:

    private void table_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        if (((MyData)e.Row.DataContext).Module.Trim().Equals("SomeText"))
        {
            e.Row.Foreground = new SolidColorBrush(Colors.Red);
        }
    }

【讨论】:

    【解决方案2】:

    您可以使用DataTriggerConverter

    <DataGrid ItemsSource="{Binding YourItemsSource}">
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow"> 
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Count_Of_Failure}" Value="0">
                        <Setter Property="Foreground" Value="Red"></Setter>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Count_Of_Failure}" Value="1">
                        <Setter Property="Foreground" Value="Green"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>
    

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 2013-10-17
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多