后台数据绑定
用户场景是生成报表,展示公司各员工每个月的绩效
数据结构
包括报表和单个员工绩效两个实体
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.cs
其他:列头重复解决方案
当前用户场景,如果遇到行列互换,即将员工姓名和月份互换,可能出现列名相同的问题(员工同名),则最好将列头绑定改为员工姓名+员工编号,保证唯一性,前端只显示名称,绑定"名称+ID"
前端数据绑定
数据结构
包括教师和教师信息扩展两个实体
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