我希望创建一个下拉列表作为属性的编辑器;如果下拉列表中只有字符串作为选项,使用StringConverter可以很好地工作。然而,当我尝试使用对象列表而不是字符串时,它就无法正常工作(注意,它对于普通的组合框可以正常工作!) 这是我的代码:
public static List<Bar> barlist;
public Form1()
{
InitializeComponent();
barlist = new List<Bar>();
for (int i = 1; i < 10; i++)
{
Bar bar = new Bar();
bar.barvalue = "BarObject " + i;
barlist.Add(bar);
comboBox1.Items.Add(bar);
}
Foo foo = new Foo();
foo.bar = new Bar();
propertyGrid1.SelectedObject = foo;
}
public class Foo
{
Bar mybar;
[TypeConverter(typeof(BarConverter))]
public Bar bar
{
get { return mybar; }
set { mybar = value; }
}
}
public class Bar
{
public String barvalue;
public override String ToString()
{
return barvalue;
}
}
class BarConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(barlist);
}
}
点击一个条目会给我这个:
(对于德语文本我很抱歉,我不确定是否可以更改,我的 VS 是英文的,但我的操作系统不是,错误消息是
Invalid property value.
The object of type "System.String" cannot be converted to type
"XMLTest.Form1+Bar".
我相信我可以通过定义反向转换工具来解决这个问题,将字符串转换回Bar对象。为了使其正常工作,这将需要使用不同的键。有没有更好的方法?为什么嵌入到propertyGrid控件中的comboBox使用字符串(普通的comboBox在处理此问题时没有任何问题)
此外,我能否通过编程方式更改中间分隔符的位置?我还没有找到这个选项。
谢谢。