0
比方說,我有一個具有整數屬性的類,我想在PropertyGrid中顯示該類。現在,PropertyGrid不應該簡單地顯示整數值,而是顯示列表中相應的字符串值,並進一步顯示包含該屬性可能值(也是字符串)的下拉列表。爲PropertyGrid中的int屬性提供字符串
我知道我必須爲此使用TypeConverter,並且我已經在過去爲字符串屬性做了這個。但我無法弄清楚如何做到這一點。正如你可以從我的代碼看,我完全無助:
class MyClassConverter : TypeConverter
{
List<string> values = new List<string>();
public MyClassConverter()
{
values.Add("Value1");
values.Add("Value2");
values.Add("Value3");
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
bool ret = true; //base.CanConvertFrom(context, sourceType);
Debug.Print("CanConvertFrom: " + sourceType.ToString() + " " + ret.ToString());
return ret;
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
bool ret = base.CanConvertTo(context, destinationType);
Debug.Print("CanConvertTo: " + destinationType.ToString() + " " + ret.ToString());
return ret;
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
Debug.Print("ConvertFrom: " + value.GetType().ToString());
//return base.ConvertFrom(context, culture, value);
for (int i = 0; i < values.Count; i++)
{
if (values[i] == value)
{
return i;
}
}
return -1;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
Debug.Print("ConvertTo: " + destinationType.ToString());
return base.ConvertTo(context, culture, value, destinationType);
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
Debug.Print("GetStandardValues");
StandardValuesCollection collection = new StandardValuesCollection(values);
return collection;
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
}
最快的修復將使得物業枚舉類型,不是嗎? –
那麼不在我的情況。列表中的值由用戶輸入。 –