【问题标题】:Changing specific wpf datagrid row color using c#使用 c# 更改特定的 wpf datagrid 行颜色
【发布时间】:2019-05-22 11:02:09
【问题描述】:

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

我在数据网格的 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;
        }
      }                                       
    }

此代码在加载数据网格时工作正常,但经过一段时间后,数据网格中每一行的颜色开始变化,随着时间的推移,整个网格变为红色

【问题讨论】:

  • 你有没有尝试在这个类中做一个字段(例如int_lastIndex),并且在MessagesDataGrid_LoadingRow中,在设置新行背景色为红色之前,先设置上一行索引(_lastIndex)背景色变成白色,还是变成红色之前的样子?
  • DataGridLoadingRow 事件将在您加载 DataGrid 中的项目时调用一次。根据 DataGrid 单元格的内容(基于集合的属性)更改 DataGrid Row 背景颜色,例如 Code var ds = e.Row.Item as TestEnableButton; if(ds.IsEnableButton) e.Row.Background = Brushes.Red;

标签: c# .net wpf


【解决方案1】:

我会在您绑定的类对象中结合网格样式来执行此操作。首先,您的数据显示在网格中。这是如何/从哪里来的。它是某种 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 触发的标志基础,无论您在哪里滚动记录。

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2010-12-03
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多