C# 如何将对象类型绑定到DataGrid
我有一个绑定到ObservableCollection的DataGrid 我想知道的是:如果不需要查看项目和检索对象类型,我是否可以使用实际的DataGrid对象和ItemSource来查找对象类型 因此,如果我有以下几点:C# 如何将对象类型绑定到DataGrid,c#,wpf,wpfdatagrid,C#,Wpf,Wpfdatagrid,我有一个绑定到ObservableCollection的DataGrid 我想知道的是:如果不需要查看项目和检索对象类型,我是否可以使用实际的DataGrid对象和ItemSource来查找对象类型 因此,如果我有以下几点: DataGrid dg = DataGridObject as DataGrid; Console.WriteLine("binding5=" + dg.ItemsSource.GetType()); output = System.Collections.Objec
DataGrid dg = DataGridObject as DataGrid;
Console.WriteLine("binding5=" + dg.ItemsSource.GetType());
output = System.Collections.ObjectModel.ObservableCollection`1[UserManagement.UserViewModel]
我能否以某种方式将
UserManagement.UserViewModel
提取到对象变量中如果我理解正确,您希望找出集合中设置为DataGrid.ItemsSource
属性的对象类型。为此,可以使用一些基本反射。试试这个:
var collection = ListBox.ItemsSource;
Type collectionType = collection.GetType();
Type itemType = collectionType.GetGenericArguments().Single();
如果我理解正确,您希望找出集合中设置为
DataGrid.ItemsSource
属性的对象类型。为此,可以使用一些基本反射。试试这个:
var collection = ListBox.ItemsSource;
Type collectionType = collection.GetType();
Type itemType = collectionType.GetGenericArguments().Single();
假设集合类型为
ObservableCollection
给你
Type collectionType = dg.ItemsSource.GetType();
if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition().IsAssignableFrom(typeof(ObservableCollection<>)))
{
Type objType = collectionType.GenericTypeArguments[0];
}
Type collectionType=dg.ItemsSource.GetType();
if(collectionType.IsGenericType&&collectionType.GetGenericTypeDefinition().IsAssignableFrom(typeof(ObservableCollection)))
{
类型objType=collectionType.GenericTypeArguments[0];
}
在这里,我们将确认类型是否为泛型类型,其泛型定义是否可从
ObservableCollection
赋值,然后将采用第一个类型参数,该参数将是元素的类型,假设集合的类型为ObservableCollection
给你
Type collectionType = dg.ItemsSource.GetType();
if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition().IsAssignableFrom(typeof(ObservableCollection<>)))
{
Type objType = collectionType.GenericTypeArguments[0];
}
Type collectionType=dg.ItemsSource.GetType();
if(collectionType.IsGenericType&&collectionType.GetGenericTypeDefinition().IsAssignableFrom(typeof(ObservableCollection)))
{
类型objType=collectionType.GenericTypeArguments[0];
}
在这里,我们将确认类型是否为泛型类型,其泛型定义是否可从
ObservableCollection
赋值,然后将采用第一个类型参数,即元素的类型作者所说的问题,而无需查看项并检索对象类型。。。记住@Sajeetharan,你能解释一下一个foreach
循环会有什么帮助吗?@Sheridan你是对的,我无法完整地阅读问题作者说的问题,而没有查看项目和检索对象类型。。。记住@Sajeetharan,你能解释一下foreach
循环会有什么帮助吗?@Sheridan你是对的,我无法完全理解这个问题