复合对象上的属性网格

问题描述 投票:0回答:1

当我绑定这个对象时

public class MyObject
{ 
  public AgeWrapper Age
{
get;
set;
}
}

public class AgeWrapper
{
public int Age
{
get;
set;
}
}

对于属性网格,属性网格的值部分显示的是AgeWrapper的类名,但是AgeWrapper.Age的值。

是否有办法在属性网格中显示复合对象的值(在本例中为 AgeWrapper.Age),而不是该复合对象的类名?

c# propertygrid
1个回答
6
投票

您需要创建一个类型转换器,然后使用属性将其应用到 AgeWrapper 类。然后属性网格将使用该类型转换器来显示要显示的字符串。创建一个像这样的类型转换器...

public class AgeWrapperConverter : ExpandableObjectConverter
{
  public override bool CanConvertTo(ITypeDescriptorContext context, 
                                    Type destinationType)
  {
    // Can always convert to a string representation
    if (destinationType == typeof(string))
      return true;

    // Let base class do standard processing
    return base.CanConvertTo(context, destinationType);
  }

  public override object ConvertTo(ITypeDescriptorContext context, 
                                   System.Globalization.CultureInfo culture, 
                                   object value, 
                                   Type destinationType)
  {
    // Can always convert to a string representation
    if (destinationType == typeof(string))
    {
      AgeWrapper wrapper = (AgeWrapper)value;
      return "Age is " + wrapper.Age.ToString();
    }

    // Let base class attempt other conversions
    return base.ConvertTo(context, culture, value, destinationType);
  }  
}

注意它继承自ExpandableObjectConverter。这是因为 AgeWrapper 类有一个名为 AgeWrapper.Age 的子属性,需要通过网格中 AgeWrapper 条目旁边的 + 按钮来公开该属性。如果您的类没有任何您想要公开的子属性,则可以从 TypeConverter 继承。现在将此转换器应用到您的班级...

[TypeConverter(typeof(AgeWrapperConverter))]
public class AgeWrapper
© www.soinside.com 2019 - 2024. All rights reserved.