Search code examples
c#wpfwpfdatagrid

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


Solution

  • 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();