我具有以下数据结构:
public class TimeData
{
public Employee Employee { get; set; }
public IList<WorkTime> WorkTimes { get; set; }
}
ViewModel:
public ObservableCollection<TimeData> TimeDatas { get; set; }
在我的数据网格中,我想显示所有工作时间。按员工分组。 像这样:
日期|营业时间时间码
Jon Doe
12/03/19 | 8 | 433
13/03/19 | 8 | 433
14/03/19 | 5 | 546
迈克·穆斯特
12/03/19 | 4 | 653
13/03/19 | 3 | 433
14/03/19 | 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(雇员)和Employee(雇员)即可进行分组。
答案 0 :(得分:1)
您需要将数据转换为DataGrid
可以处理的格式。创建一个包含所有属性的视图模型类:
public class EmployeeAndWorkTime
{
public string Name { get; set; }
public DateTime Date { get; set; }
public double Hours { get; set; }
public string TimeCode { get; set; }
}
...并绑定到您从现有IEnumerable<EmployeeAndWorkTime>
集合创建的TimeDatas
:
TransformedTimeDatas = TimeDatas.Select(timeData =>
{
EmployeeAndWorkTime[] viewModels = new EmployeeAndWorkTime[timeData.WorkTimes.Count];
for (int i = 0; i < timeData.WorkTimes.Count; ++i)
viewModels[i] = new EmployeeAndWorkTime()
{
Name = string.Format("{0} {1}", timeData.Employee.FirstName, timeData.Employee.LastName),
Date = timeData.WorkTimes[i].Date,
Hours = timeData.WorkTimes[i].Hours,
TimeCode = timeData.WorkTimes[i].TimeCode
};
return viewModels;
}).ToArray();
ListCollectionView collectionView = new ListCollectionView(TransformedTimeDatas);
collectionView.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
this.grdTimeData.ItemsSource = collectionView;