我试图在WPF中创建一个库,用于从可观察的集合中创建报表,但我不知道如何循环使用。ObservableCollection
将数值写入 FlowDocument
表。我试着把通用集合投到一个 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
.
谁能告诉我如何正确地做到这一点?
P.S.: 正如你所看到的,我遵循的是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()。
对于获取属性和为新单元格添加值,类似这样的东西可能会有用。
var props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var p in props)
{
my_cell.Cells.Add(new TableCell(new Paragraph(new Run(p.GetValue(this).ToString()))) { Padding = new Thickness(2), BorderBrush = Brushes.Black, BorderThickness = new Thickness(0.7) });
}