简体   繁体   中英

How to get the PropertyType of indexed property in WPF

I am working with DataBinding in DataGrid. I have a viewmodel which has a property called MyDataSource of type List. Class1 has a property called MyList of type List. Class2 has a property called MyProperty of type string.

My DataGrid xaml looks like.

<DataGrid ItemsSource="{Binding MyDataSource}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="MyValue" Binding="{Binding Path=MyList[0].MyProperty}"/>
        </DataGrid.Columns>
</DataGrid>

Here I have access to PropertyPath MyList[0].MyProperty and MyDataSource in code. Now I want to find out PropertyType for MyProperty by passing MyList[0].MyProperty in GetProperty method.

I followed the method described in the following link. But here the PropertyInfo is null for MyList[0]. http://www.java2s.com/Code/CSharp/Reflection/Getsapropertysparentobject.htm

Edited:

I also tried the following code:

PropertyInfo pInfo = MyDataSource.GetType().GetProperty(MyList[0].MyProperty)

But pInfo returns null here.

Can anybody please suggest me a solution?

Not sure what you want to achieve but you could use a ValueConverter like:

  class MyConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      var typeName = ((Class2)value).GetType().GetProperty((string) parameter);
      return typeName.ToString();
    }

And XAML Binding:

<Window x:Class="ThemeTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:conv="clr-namespace:ThemeTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <conv:MyConverter x:Key="propertyToParentTypeConverter"/>
    </Window.Resources>

...

    <DataGrid ItemsSource="{Binding MyDataSource}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="MyValue">
                <DataGridTextColumn.Binding>
                    <Binding Converter="{StaticResource propertyToParentTypeConverter}"  ConverterParameter="MyProperty" Path="MyList[0]" />
                </DataGridTextColumn.Binding>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

If you need to traverse a chain of properties where one property is a collection then you can use reflection in the following way:

  PropertyInfo pInfo = myObject.GetType().GetProperty("MyDataSource");
  if (pInfo != null && pInfo.PropertyType.FullName.StartsWith("System.Collections"))
  {
    foreach (object obj in ((IEnumerable)pInfo.GetValue(myObject, null)))
    {
      PropertyInfo pInfoElement = obj.GetType().GetProperty("MyList");
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM