ACCESS A PROPERTY OF IENUMERABLE

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
C# 
C#
 1040  View(s)
Ratings:
Rate this:

I have a custom class for a combobox having following properties:

public IEnumerable<object> ItemsSource

{

    get { return (IEnumerable<object>)GetValue(ItemsSourceProperty); }

    set

    {

        SetValue(ItemsSourceProperty, value);

    }

}

public string DisplayMemberPath

{

    get { return (string)GetValue(DisplayMemberPathProperty); }

    set { SetValue(DisplayMemberPathProperty, value); }

}

where ItemsSourceProperty,DisplayMemberPathProperty are the dependency properties already registered.

Now if ItemSource has a list of custom objects :{id int, name string}. and DisplayMemberPath has value:'name' or 'id'. How can I access 'name' or 'id' properties of my object ?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Access a property of IEnumerable

    Hi Jayden,


    It's not entirely clear why you need to do this binding yourself (when WPF does a lot of this for you), but this might work:

    foreach (object item in ItemsSource)

    {

        var property = item.GetType().GetProperty(DisplayMemberPath);

        var value = property.GetValue(item, null);

        // Use the value here

    }

    Note that this will be pretty slow, and will only handle a single property name (rather than a full path). There are more complex alternatives which would perform better, but I'd probably go with the simplest approach first.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!