2008-10-28 81 views
2

當我綁定此對象屬性網格上的組合對象

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

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

的屬性網格,什麼是顯示在屬性網格的價值部分是AgeWrapper的類名,但AgeWrapper.Age值。

是否有無論如何使它在屬性網格中可以顯示組合對象的值(在這種情況下,它是AgeWrapper.Age),而不是該組合對象的類名稱?

回答

5

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