使用C#更改特定的WPF DataGrid行颜色

时间:2019-05-22 11:02:10

标签: c# .net wpf

我需要在运行时更改特定数据网格行的颜色

我正在数据网格的Loading Row事件中设置行背景颜色

 private void MessagesDataGrid_LoadingRow(objects , DataGridRowEventArgs e)
   {           
      var v = e.Row.Item.ToString();
      int i = e.Row.GetIndex();
      if (IoStatusViewModel.HighlightSelected == true  )
      {
         e.Row.Focusable = true;
         e.Row.Background = Brushes.Red;
         if (v.Contains("MCP :"))
         {
             DisplayLogs = IoStatusViewModel.ChangeMcpLog(v);
             e.Row.Item = DisplayLogs;
         }
      }          
     else
     {
        if (v.Contains("MCP :"))
        {
         DisplayLogs = IoStatusViewModel.ChangeMcpLog(v);
         e.Row.Item = DisplayLogs;
        }
      }                                       
    }

此代码在加载数据网格时工作正常,但是一段时间后,数据网格中每行的颜色开始改变,随着时间的流逝,整个网格变成红色

1 个答案:

答案 0 :(得分:2)

我将在您要绑定的类对象中结合网格样式来执行此操作。首先,您的数据将显示在网格中。这是怎么来的/从哪里来的。是某种List <>或ObservableCollect <>项。例子

var yourBoundProperty = new List<SomeClass>();

…随便填充。

public class SomeClass
{
   public string SomeProp {get; set;}
   public string YourMCPField {get; set;}
   // make a SPECIAL FIELD... could be boolean, number setting, whatever flag
   // but in this case, I just have boolean
   public bool FieldContainsMCP { get { return YourMCPFieldContains( "MCP :"); }}
}

现在,在您的Xaml中...假设在Window声明中。

<Window … >
   <Window.Resources>
      <Style TargetType="{x:Type DataGridCell}" x:Key="MyColorTriggers">
         <Style.Triggers>
            <DataTrigger Binding="{Binding FieldContainsMCP}" Value="True">
               <Setter Property="Background" Value="Red" />
               <Setter Property="ExampleAnyOtherProperty" Value="someOtherValue" />
            </DataTrigger>
         </Style.Triggers>
      </Style>
   </Window.Resources>


   <DataGrid  … other settings you have
      CellStyle="{StaticResource MyColorTriggers}" >

      .. rest of your data column declarations

   </DataGrid>
</Window>

通过这种方式,实际的数据源是标记的基础,无论您在何处滚动记录,该标记都将应用于CellStyle触发。