How to get Object type bound to DataGrid

喜你入骨 提交于 2019-12-25 06:23:26

问题


I have a DataGrid that is bound to ObservableCollection.

What I am wondering is: without resorting to looking at an item and retrieving the object type, can I somehow use the actual DataGrid object and the ItemSource to find the type of objects?

So if I have the following:

DataGrid dg = DataGridObject as DataGrid;
Console.WriteLine("binding5=" + dg.ItemsSource.GetType());



output = System.Collections.ObjectModel.ObservableCollection`1[UserManagement.UserViewModel]

Can I extract UserManagement.UserViewModel into an object variable somehow


回答1:


If I understand you correctly, you want to find out the type of object inside the collection that is set as the DataGrid.ItemsSource property. To do this, you can use some basic reflection. Try this:

var collection = ListBox.ItemsSource;
Type collectionType = collection.GetType();
Type itemType = collectionType.GetGenericArguments().Single();



回答2:


with assumption that the collection is of type ObservableCollection<>

here you go

        Type collectionType = dg.ItemsSource.GetType();

        if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition().IsAssignableFrom(typeof(ObservableCollection<>)))
        {
            Type objType = collectionType.GenericTypeArguments[0];
        }

here we will confirm if the type is a generic type and its generic definition is assignable from ObservableCollection<> then will take the first type argument which will be the type of elements



来源:https://stackoverflow.com/questions/24670990/how-to-get-object-type-bound-to-datagrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!