绑定此对象时

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

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

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

无论如何要使它在属性网格中我可以显示复合对象的值(在这种情况下,它是AgeWrapper.Age),而不是该复合对象的类名吗?

有帮助吗?

解决方案

您需要创建一个类型转换器,然后使用属性将其应用于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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top