DataGrid数据绑定
生活随笔
收集整理的這篇文章主要介紹了
DataGrid数据绑定
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
后臺數據綁定
用戶場景是生成報表,展示公司各員工每個月的績效
數據結構
包括報表和單個員工績效兩個實體
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
轉載于:https://www.cnblogs.com/Lulus/p/9726375.html
總結
以上是生活随笔為你收集整理的DataGrid数据绑定的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SELinux 引起的 Docker 启
- 下一篇: Python学习 - 之super函数