访问IEnumerable的属性

zoo*_*ney 3 c# reflection ienumerable custom-controls wpf-controls

我有一个具有以下属性的组合框的自定义类:

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); }
}
Run Code Online (Sandbox Code Playgroud)

其中ItemsSourceProperty,DisplayMemberPathProperty已注册的依赖属性.

现在,如果ItemSource有一个自定义对象列表:{id int,name string}.和DisplayMemberPath具有值:'name'或'id'.如何访问对象的"名称"或"id"属性?`

Jon*_*eet 5

现在还不完全清楚为什么你需要自己做这个绑定(当WPF为你做了很多这样的事情时),但这可能有效:

foreach (object item in ItemsSource)
{
    var property = item.GetType().GetProperty(DisplayMemberPath);
    var value = property.GetValue(item, null);
    // Use the value here
}
Run Code Online (Sandbox Code Playgroud)

请注意,这将非常慢,并且只处理单个属性名称(而不是完整路径).有更复杂的替代方案会表现得更好,但我可能会先采用最简单的方法.