您需要創建一個類型轉換器,然後將該屬性應用於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