我想创建一个下拉列表作为属性的编辑器;如果我只有字符串作为下拉列表的条目,这将正常工作(使用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没有任何问题处理这个)
最重要的是,我可以通过编程方式更改中间分隔符的位置吗?我还没有找到那个选项.
谢谢.
解决方法
我将CanConvertFrom和ConvertFrom方法添加到您的转换类:
- class BarConverter : TypeConverter
- {
- public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
- {
- return true;
- }
- public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
- {
- return new StandardValuesCollection(barlist);
- }
- public override bool CanConvertFrom(ITypeDescriptorContext context,Type sourceType)
- {
- if (sourceType == typeof(string))
- {
- return true;
- }
- return base.CanConvertFrom(context,sourceType);
- }
- public override object ConvertFrom(ITypeDescriptorContext context,System.Globalization.CultureInfo culture,object value)
- {
- if (value is string)
- {
- foreach (Bar b in barlist)
- {
- if (b.barvalue == (string)value)
- {
- return b;
- }
- }
- }
- return base.ConvertFrom(context,culture,value);
- }
- }