c# - 迭代 ObservableCollection价值观
问题描述
我正在尝试创建一个库,用于从可观察的集合在 WPF 中创建报告,但我不知道如何循环ObservableCollection
将值写入FlowDocument
表中。我尝试将通用集合转换为 a IEnumerable
,但我不断得到
抛出异常:'System.NullReferenceException'
目标是编写一个可以接受所有ObservableCollection
类型的库,所以我编写了这个类(片段):
public class Report_Definition<T> : INotifyPropertyChanged
{
public Report_Definition(FlowDocument doc, ObservableCollection<T> data)
{
Fill_data(data, doc);
}
private void Fill_data(ObservableCollection<T> data, FlowDocument doc)
{
//I only take 25 records from ObservableCollection - to create more Tables
for (int i = 0; i < data.Count; i += 25)
{
var list = (from c in data select c).Skip(i).Take(25);
if (i < 25) //Test for only first Table
{
for (int row = 0; row < list.Count(); row++)
{
TableRow my_cell = new TableRow();
foreach (var item in list)
{
foreach (var w in item as IEnumerable<T>) //ERROR HERE !!!
{
my_cell.Cells.Add(new TableCell(new Paragraph(new Run(w.ToString()))) { Padding = new Thickness(2), BorderBrush = Brushes.Black, BorderThickness = new Thickness(0.7) });
}
}
TableRowGroup whole_row = new TableRowGroup();
whole_row.Rows.Add(my_cell);
My_table.RowGroups.Add(whole_row); //I get reference of this elsewhere...
}
}
}
}
这是我的Employee
课:
public class Employee : INotifyPropertyChanged
{
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
public string Country { get; set; }
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
因此,在大写中我使用ObservableCollection(Employee)
,并且我想遍历Employee
此集合中的每个以在表行中写入值。
目前此代码仅将类型写入单元格,例如My_Project.Model.Employee
.
有人可以告诉我如何正确地做到这一点吗?
PS:如您所见,我正在遵循 MVVM 方法。
解决方案
假设这是您拥有的课程
public class Employee
{
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
public string Country { get; set; }
}
下面的代码将产生以下输出
var props = typeof(Employee).GetProperties();
var employee = new Employee { Name = "Athul", Surname = "Raj", Address = "Blah", Country = "India" };
foreach (var prop in props)
{
Console.WriteLine($"{prop.Name} = {prop.GetValue(employee)}");
}
Console.ReadKey();
.
Name = Athul
Surname = Raj
Address = Blah
Country = India
您可以在方法中使用 typeof(T).GetProperties() 而不是 typeof(Employee).GetProperties()
推荐阅读
- javascript - settimeout 函数中的异步返回承诺
- ios - 部分文本隐藏在 Swift TextField 中
- javascript - 从 Contentful 检索降价时,Gatsby “尝试获取资源时出现网络错误”
- reactjs - 如何在 jest React 中为函数编写单元测试用例?
- vue.js - ERR_NAME_NOT_RESOLVED socketIO
- android - Android Studio 3.6.3 未在 build.gradle 中显示依赖项更新
- sql - SQLite OR 运算符
- npm - 在单个 git 分支上升级 NPM
- scala - 在 spark scala 中减少为单列
- javascript - PHP / MySQL:多次删除出错,只删除了最新的ID