简体   繁体   中英

How to change Datagrid row color at runtime in wpf?

I am using WPF DataGrid and adding rows at runtime by using a class 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 });

Used the below Loading Row event code for changing color of the datagrid row. But its not working.

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

Can anybody tell me the solution?

Because it row event there it is the worng place to do it, here you can place a condition about the row:

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

You can do with a DataTrigger or Converter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM