简体   繁体   中英

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

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

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