用户场景是生成报表,展现公司各员工每月的绩效前端
包括报表和单个员工绩效两个实体git
public class Report { /// <summary> /// 统计时间 /// </summary> public string StatisticalDate { get; set; } public List<ReportDetail> ReportDetails { get; set; } }
public class ReportDetail { /// <summary> /// 职员姓名 /// </summary> public string EmployeeName { get; set; } /// <summary> /// 统计数据 /// </summary> public decimal Data { get; set; } }
DataGrid dataGrid = new DataGrid(); var _ds = new DataSet("Test"); Dt = _ds.Tables.Add("月度绩效表"); //create columns //建立列 Dt.Columns.Add("月份"); foreach (var item in reports[0].ReportDetails) { Dt.Columns.Add(item.EmployeeName); } //fill data to rows //赋值数据 for(int i=0;i< reports.Count;i++) { var theRow = Dt.NewRow(); theRow[0] = reports[i].StatisticalDate; for (int j = 0; j < reports[i].ReportDetails.Count; j++) { theRow[j+1] = reports[i].ReportDetails[j].Data; } Dt.Rows.Add(theRow); } //数据绑定 dataGrid.ItemsSource = Dt.AsDataView(); //将控件添加到Grid MyGrid.Children.Add(dataGrid);
https://github.com/zLulus/NotePractice/blob/dev3/WPF/WpfDemo/Bind/DataGridBackgroundBind.xaml
https://github.com/zLulus/NotePractice/blob/dev3/WPF/WpfDemo/Bind/DataGridBackgroundBind.xaml.csgithub
当前用户场景,若是遇到行列互换,即将员工姓名和月份互换,可能出现列名相同的问题(员工同名),则最好将列头绑定改成员工姓名+员工编号,保证惟一性,前端只显示名称,绑定"名称+ID"c#
包括教师和教师信息扩展两个实体数据结构
public class Teacher { public string SchoolNumber { get; set; } public string Name { get; set; } public string Sex { get; set; } public TeacherDetailInfo TeacherDetailInfo { get; set; } }
public class TeacherDetailInfo { public DateTime EntryTime { get; set; } public string Address { get; set; } }
<DataGrid ItemsSource="{Binding }" AutoGenerateColumns="False" CanUserAddRows="False"> <DataGrid.Columns> <DataGridTextColumn Header="编号" Binding="{Binding SchoolNumber}"/> <DataGridTextColumn Header="姓名" Binding="{Binding Name}"/> <DataGridTextColumn Header="性别" Binding="{Binding Sex}"/> <!--格式化日期--> <DataGridTextColumn Header="入职时间" Binding="{Binding Path=TeacherDetailInfo.EntryTime, StringFormat=\{0:yyyy年MM月dd日\}}"/> <!--若是这里是双向绑定,则是下面的写法,Mode是双向(TwoWay),触发器是变化即触发--> <!--<DataGridTextColumn Header="入职时间" Binding="{Binding Path=TeacherDetailInfo.EntryTime,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>--> <DataGridTextColumn Header="住址" Binding="{Binding Path=TeacherDetailInfo.Address}"/> </DataGrid.Columns> </DataGrid>
https://github.com/zLulus/NotePractice/blob/dev3/WPF/WpfDemo/Bind/DataGridBindMultiData.xaml
https://github.com/zLulus/NotePractice/blob/dev3/WPF/WpfDemo/Bind/DataGridBindMultiData.xaml.cs双向绑定