c# – PropertyGrid控件和下拉列表

前端之家收集整理的这篇文章主要介绍了c# – PropertyGrid控件和下拉列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_0@
我想创建一个下拉列表作为属性的编辑器;如果我只有字符串作为下拉列表的条目,这将正常工作(使用StringConverter).但是,当我尝试使用对象列表而不是字符串时,这不起作用(注意它对于正常的组合框是如何工作的!)
这是我的代码
  1. public static List<Bar> barlist;
  2. public Form1()
  3. {
  4. InitializeComponent();
  5. barlist = new List<Bar>();
  6. for (int i = 1; i < 10; i++)
  7. {
  8. Bar bar = new Bar();
  9. bar.barvalue = "BarObject " + i;
  10. barlist.Add(bar);
  11. comboBox1.Items.Add(bar);
  12. }
  13. Foo foo = new Foo();
  14. foo.bar = new Bar();
  15. propertyGrid1.SelectedObject = foo;
  16. }
  17.  
  18. public class Foo
  19. {
  20. Bar mybar;
  21.  
  22. [TypeConverter(typeof(BarConverter))]
  23. public Bar bar
  24. {
  25. get { return mybar; }
  26. set { mybar = value; }
  27. }
  28. }
  29.  
  30. public class Bar
  31. {
  32. public String barvalue;
  33. public override String ToString()
  34. {
  35. return barvalue;
  36. }
  37. }
  38.  
  39.  
  40. class BarConverter : TypeConverter
  41. {
  42. public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
  43. {
  44. return true;
  45. }
  46.  
  47. public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
  48. {
  49. return new StandardValuesCollection(barlist);
  50. }
  51. }

结果(嵌入到表单等)看起来像这样:

点击一个条目给了我这个:

(抱歉德语文本,我不确定我是否可以改变它,我的VS是英语但我的操作系统不是,错误信息是

  1. Invalid property value.
  2.  
  3. The object of type "System.String" cannot be converted to type
  4. "XMLTest.Form1+Bar".

我非常确定我可以通过定义将字符串转换回Bar对象的向后转换工具来解决此问题.这将需要键不同才能使其正常工作.这样做有更好的方法吗?为什么嵌入到propertyGrid控件中的comboBox使用字符串(正常的comboBox没有任何问题处理这个)

最重要的是,我可以通过编程方式更改中间分隔符的位置吗?我还没有找到那个选项.

谢谢.

解决方法

我将CanConvertFrom和ConvertFrom方法添加到您的转换类:
  1. class BarConverter : TypeConverter
  2. {
  3. public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
  4. {
  5. return true;
  6. }
  7.  
  8. public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
  9. {
  10. return new StandardValuesCollection(barlist);
  11. }
  12.  
  13. public override bool CanConvertFrom(ITypeDescriptorContext context,Type sourceType)
  14. {
  15. if (sourceType == typeof(string))
  16. {
  17. return true;
  18. }
  19. return base.CanConvertFrom(context,sourceType);
  20. }
  21.  
  22. public override object ConvertFrom(ITypeDescriptorContext context,System.Globalization.CultureInfo culture,object value)
  23. {
  24. if (value is string)
  25. {
  26. foreach (Bar b in barlist)
  27. {
  28. if (b.barvalue == (string)value)
  29. {
  30. return b;
  31. }
  32. }
  33. }
  34. return base.ConvertFrom(context,culture,value);
  35. }
  36. }

猜你在找的C#相关文章