Property Grid on Composite objects

我是研究僧i 提交于 2019-12-12 19:09:18

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/241887/property-grid-on-composite-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!