Reputation: 2626
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
Upvotes: 1
Views: 1804
Reputation: 13679
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
Upvotes: 1
Reputation: 69989
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();
Upvotes: 4