我需要使用WPF中的DataGrid控件的System.Collections.IEnumerable来获取模型类属性列表。
DataGrid Control具有属性public IEnumerable ItemsSource { get; set; }
考虑为ItemsSource分配以下列表:List<Person> EmpList
void Main()
{
List<Person> EmpList = new List<Person>()
{
new Person() {ID = 101, Name = "Peter", Gender = "Male", Role = "Manager"},
new Person() {ID = 102, Name = "Emma Watson", Gender = "Female", Role = "Assistant"},
new Person() {ID = 103, Name = "Kaliya", Gender = "Manager", Role = "Assistant"},
};
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Role { get; set; }
}
我需要使用public IEnumerable ItemsSource { get; set; }
我使用List<Person> EmpList
EmpList.GetType()
.GetInterfaces()
.Where(t => t.IsGenericType == true
&& t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(t => t.GetGenericArguments()[0])
.FirstOrDefault().GetProperties()
.Select(x => x.Name).ToList();
上述查询的输出是
像这样我需要使用 DataGrid ItemsSource
获取模型属性我在Datagrid控件类中使用this.ItemsSource
尝试了它,但我无法获取List。但ItemsSource充满了3个与上述集合相同的集合。
this.ItemsSource.GetType()
.GetInterfaces()
.Where(t => t.IsGenericType == true
&& t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(t => t.GetGenericArguments()[0])
.FirstOrDefault().GetProperties()
.Select(x => x.Name).ToList().Dump();
我需要使用this.ItemsSource
提供与上面相同的输出。请帮助我如何实现这个???
我尝试了@bhuvin方法 - 反思,但我得到了空结果
逐步拍摄类型信息和属性信息快照
类型信息:
物业资讯:
答案 0 :(得分:0)
using System.Reflection; // reflection namespace
// get all public static properties of ObjList's type
PropertyInfo[] propertyInfos;
//objList might be any type of Collection.
propertyInfos = objList.GetType().GetProperties(BindingFlags.Public |
BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{ return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
Console.WriteLine(propertyInfo.Name);
}
答案 1 :(得分:0)
假设PersonsGrid是Datagrid控件的名称,以下代码应返回所需的数据:
Type itemType = PersonsGrid.ItemsSource.GetType().GetGenericArguments()[0];
var propertyNames = itemType.GetProperties().Select(x => x.Name);