【问题标题】:Property Grid on Composite objects复合对象上的属性网格
【发布时间】:2008-10-28 00:51:54
【问题描述】:

当我绑定这个对象时

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

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

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

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

【问题讨论】:

    标签: c# propertygrid


    【解决方案1】:

    您需要创建一个类型转换器,然后使用属性将其应用到 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-04
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2011-09-28
      相关资源
      最近更新 更多