views:

628

answers:

1

When I bind this object

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

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

to a property grid, what is shown in the value section of the property grid is the class name of AgeWrapper, but the value for AgeWrapper.Age.

Is there anyway to make it so that in the property grid I can show the value of the composite object ( in this case, it's AgeWrapper.Age), instead of the class name of that composite object?

+3  A: 

You need to create a type converter and then apply that using an attribute to the AgeWrapper class. Then the property grid will use that type converter for getting the string to display. Create a type converter like this...

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);
  }  
}

Notice that it inherits from ExpandableObjectConverter. This is because the AgeWrapper class has a child property called AgeWrapper.Age that needs to be exposed by having a + button next to the AgeWrapper entry in the grid. If your class did not have any child properties that you wanted to expose then instead inherit from TypeConverter. Now apply this converter to your class...

[TypeConverter(typeof(AgeWrapperConverter))]
public class AgeWrapper
Phil Wright