WPF DataGrid行/列/单元格高亮显示

4
我正在我的项目中实现数据差异比较,现在我需要向用户显示我的结果。 (我正在检查两个任意数据的数组并找出它们之间的不匹配点,我的结果是这样的: “状态:不匹配,属性:…索引:…”(一些类))。到目前为止它运行得很好,起初我以为在DataGrid中突出显示结果会很容易,但是当我开始实现时,我意识到我根本无法想象如何完成这项工作...我需要突出预设单元格和行...是否存在常见的解决方案?P.S DataGrid绑定到一些数据(使用视图)。我在WPF方面没有太多的经验,所以不想重新发明轮子,认为应该存在某些解决方案,开源项目,代码示例。
1个回答

4

以下是您需要的示例。

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

希望这能帮到您。

我尝试了这个解决方案,但并不完全符合我的要求,我需要突出显示已修改的单元格,而不是整行。如何实现? - illegal-immigrant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接