是否可以在Observable集合的array列的索引上添加分组?

时间:2019-08-02 17:14:18

标签: c# wpf grouping observablecollection icollectionview

我有一个带有预定义类的ObservableCollection,目前,该ObservableCollection使用ICollectionView显示在DataGrid中,并按sl_Id,sl_Name,sl_Date列分组。

但是我想知道是否有可能按sl_struct的索引分组,数组的长度是在运行时确定的。

public class SyncLog
{
    public string sl_ID { get; set; }
    public string sl_Name { get; set; }
    public string sl_Date { get; set; }
    public string sl_Type { get; set; }
    public string[] sl_Struct { get; set; }
    public string sl_SourceMachine { get; set; }
    public string sl_Source { get; set; }
    public string sl_DestMachine { get; set; }
    public string sl_Dest { get; set; }
    public bool sl_Success { get; set; }
    public string sl_Time { get; set; }
    public string sl_Size { get; set; }
}

当前分组代码

ICollectionView backupLogView = CollectionViewSource.GetDefaultView(Synclog);

PropertyGroupDescription group1 = new PropertyGroupDescription("sl_Id");
PropertyGroupDescription group2 = new PropertyGroupDescription("sl_Name");
PropertyGroupDescription group3 = new PropertyGroupDescription("sl_Date");

backupLogView.GroupDescriptions.Add(group1);
backupLogView.GroupDescriptions.Add(group2);
backupLogView.GroupDescriptions.Add(group3);

backupLogView.SortDescriptions.Add(new SortDescription("sl_Id", ListSortDirection.Ascending));
backupLogView.SortDescriptions.Add(new SortDescription("sl_Name", ListSortDirection.Ascending));
backupLogView.SortDescriptions.Add(new SortDescription("sl_Date", ListSortDirection.Ascending));
backupLogView.SortDescriptions.Add(new SortDescription("sl_Time", ListSortDirection.Ascending));

backupLogView.Refresh();

1 个答案:

答案 0 :(得分:2)

如果new PropertyGroupDescription("sl_Struct.Length")不起作用,尽管可能应该起作用,您可以将另一个属性添加到返回sl_Struct.Length的SyncLog类中

public class SyncLog
{
    public string[] sl_Struct { get; set; }
    public int sl_StructLength => sl_Struct?.Length ?? 0;
}
...
PropertyGroupDescription group = new PropertyGroupDescription("sl_StructLength ");

如果您无法将属性添加到SyncLog类中(例如,如果它是一些外部DTO),则您可能应该创建一个专门的SyncLogViewModel,它包装常规的SyncLog并添加sl_StructLength

public class SyncLogViewModel
{
    private readonly SyncLog _syncLog;
    public SyncLogViewModel(SyncLog syncLog) =>
         _syncLog = syncLog ?? throw new ArgumentNullException(nameof(syncLog));
    public int sl_StructLength => _syncLog.sl_Struct?.Length ?? 0;
    public int sl_Struct 
    {
         get => _syncLog.sl_Struct;
         set => _syncLog.sl_Struct = value;
    }
    // Other properties...
}