按隐藏属性对数据网格条目进行分组

我有以下数据结构:


public class TimeData

{

    public Employee Employee { get; set; }

    public IList<WorkTime> WorkTimes { get; set; }

}

视图模型:


public ObservableCollection<TimeData> TimeDatas { get; set; }

在我的数据网格中,我想显示所有工作时间。按员工分组。像这样:


日期 | 小时 | 时间码


乔恩·多伊


19 年 12 月 3 日 | 8 | 433


19 年 3 月 13 日 | 8 | 433


19 年 3 月 14 日 | 5 | 546


迈克·穆斯特


19 年 12 月 3 日 | 4 | 653


19 年 3 月 13 日 | 3 | 433


19 年 3 月 14 日 | 9 | 546


public class Employee

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

public class WorkTime

{

    public DateTime Date { get; set; }

    public double Hours { get; set; }

    public string TimeCode { get; set; }

}

我已经尝试过以下代码:


ListCollectionView collectionView = new ListCollectionView(this.viewModel.TimeDatas);

collectionView.GroupDescriptions.Add(new PropertyGroupDescription("Employee"));

this.grdTimeData.ItemsSource = collectionView;

这按员工分组,但不显示 WorkTimes 列表:

http://img.mukewang.com/6354fb5b0001459807270123.jpg

在网格行中,我只需要 WorkTimes,Employee 仅用于分组。

杨__羊羊
浏览 86回答 1
1回答

holdtom

您需要将数据转换为DataGrid可以处理的格式。创建一个包含所有属性的视图模型类:public class EmployeeAndWorkTime{&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public DateTime Date { get; set; }&nbsp; &nbsp; public double Hours { get; set; }&nbsp; &nbsp; public string TimeCode { get; set; }}...并绑定到IEnumerable<EmployeeAndWorkTime>您从现有TimeDatas集合创建的:TransformedTimeDatas = TimeDatas.Select(timeData =>{&nbsp; &nbsp; EmployeeAndWorkTime[] viewModels = new EmployeeAndWorkTime[timeData.WorkTimes.Count];&nbsp; &nbsp; for (int i = 0; i < timeData.WorkTimes.Count; ++i)&nbsp; &nbsp; &nbsp; &nbsp; viewModels[i] = new EmployeeAndWorkTime()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = string.Format("{0} {1}", timeData.Employee.FirstName, timeData.Employee.LastName),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Date = timeData.WorkTimes[i].Date,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Hours = timeData.WorkTimes[i].Hours,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TimeCode = timeData.WorkTimes[i].TimeCode&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; return viewModels;}).ToArray();ListCollectionView collectionView = new ListCollectionView(TransformedTimeDatas);collectionView.GroupDescriptions.Add(new PropertyGroupDescription("Name"));this.grdTimeData.ItemsSource = collectionView;
打开App,查看更多内容
随时随地看视频慕课网APP