简体   繁体   English

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

[英]Changing specific wpf datagrid row color using c#

I have a requirement to change color of specific data grid row at run time 我需要在运行时更改特定数据网格行的颜色

I am setting row background color inside Loading Row event of data grid 我在数据网格的加载行事件中设置行背景色

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

This code is working fine as data grid loads but after some times the color of each rows in data grid starts changing and as time passes whole grid becomes red 这段代码在数据网格加载时运行良好,但是一段时间后,数据网格中每行的颜色开始改变,随着时间的流逝,整个网格变成红色

I would do it within the class object you are binding against in conjunction with a style for the grid. 我将在您要绑定的类对象以及网格样式中执行此操作。 First, your data being presented in the grid. 首先,您的数据将显示在网格中。 How/where is that coming from. 这是怎么来的/从哪里来的。 Is it some sort of List<> or ObservableCollect<> of items. 是某种List <>或ObservableCollect <>项。 Example

var yourBoundProperty = new List<SomeClass>();

… populate however you do. …随便填充。

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

Now, in your Xaml… assuming in a Window declaration. 现在,在您的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>

This way the actual data source is the flag basis which is applied to the CellStyle triggering regardless of where you may be scrolling through records. 这样,实际数据源便是标记基础,无论您在何处滚动记录,都将其应用于CellStyle触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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