Search code examples
c#wpfdatagridhighlighting

WPF DataGrid rows/columns/cells highlighting


I'm implementing data diff in my project and now i have a need to display my results to user. (I'm inspecting two arrays of arbitrary data and finding mismatches in them, my results are something like : "Status : mismatch, Property : ... Index: ..." (some class)). So It's working pretty well by now,first I thought it will be easy to highlight results in DataGrid, but when i started to implement this i realized that I just can't imagine how to get this done...I need to highlight preset cells and rows...Does any common solution exist? P.S DataGrid is binding to some data (using views). I have no much experience in WPF, so don't want to reinvent the wheel, think something should exist (solution, open-source project, code samples).


Solution

  • Here is example of what you need.

    1. I assume, that ChangeItem is class for storing one line. So in xaml you bind ChangeItem[] to ItemsSource property of your datagrid.

      class ChangeItem
      {
          public string Previous { get; set; }
          public string Current  { get; set; }
          public bool HasDiff { return this.Previous != this.Current; } 
      }
      
    2. In Xaml add special style to your Resources

      <Style TargetType="{x:Type DataGridCell}">
          <Style.Triggers>
             <DataTrigger Binding="{Binding HasDiff}" Value="true">
                <Setter Property="Background" Value="Red"/>
             </DataTrigger>
          </Style.Triggers>
      </Style>
      
    3. If you need to support editing and real-time background changes, depending on changes made. Then properly implement INotifyPropertyChanged in class ChangeItem.

    4. If you need to have more than 2 states (HasError/NoErrors), then create new enum, representing states. For example:

      public enum LineState
      {
           Normal,
           SmallError,
           MegaError,
      }
      

      And replace public bool HasDiff { ... } property with something like public LineState State { ... }.

    Hope this helps.