Search code examples
c#wpfclassproperties

Get class properties from datagrid ItemSources


How can i get all properties of class that is an ItemSource of DataGrid.

I have some classes that I assign as item sources to the DataGrid control.

I want to access the properties of the class that I assigned as itemssource in the Preview Key Down event.

Since the class name is variable, I am trying to create a common method. Similar to the one below.

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    DataGrid grid = sender as DataGrid;
    var dataSource = grid.ItemsSource;
    foreach (var prop in dataSource.GetType().GetProperties())
    {
        
    }
}

Solution

  • how can i get first element from dataSource.

    Example: https://onlinegdb.com/O8QmfeIAa

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    
    class HelloWorld {
      static void Main() {
        IEnumerable coll = new List<string>() {"first", "second"};
        object item = coll.Cast<object>().First();
        Type itemType = item.GetType();
        foreach (var prop in itemType.GetProperties())
        {
            Console.WriteLine(prop.Name);
        }
      }
    }
    

    P.S. But if the collection is empty, then you will have to track its filling and only after adding an element determine its type.