Hank
Hank

Reputation: 2626

How to get Object type bound to DataGrid

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

Answers (2)

pushpraj
pushpraj

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

Sheridan
Sheridan

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

Related Questions