首页  :: 新随笔  :: 联系 :: 管理

   文章转载于http://www.cnblogs.com/guanjinke/archive/2006/12/15/593784.html

  前面的几篇文章中,我们给控件添加一个复杂的类型Scope,并且给它的类型提供的一个类型转换器,现在我们可以在属性浏览器中编辑它的值,并且它的值也被串行化的源代码里了。但是你有没有发现,在属性浏览器里编辑这个属性的值还是不太方便。因为属性只是“10200这种形式的,所以,你必须按照这种格式来修改,一旦格式错误就会引发异常,比如输入一个“10200。我们期望这个属性的每一子属性都能够被独立的编辑就好了,这并非不能实现,而且实现还很简单。
 为了在属性浏览器里能够独立的编辑子属性,我们还要重写两个方法:GetPropertiesSupported()和GetProperties();下面是ScopeConverter的完整代码:

1 public class ScopeConverter : TypeConverter
2 {
3 public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
4 {
5 if (sourceType == typeof(String)) return true;
6
7 return base.CanConvertFrom(context, sourceType);
8 }
9
10 public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
11 {
12 if (destinationType == typeof(String)) return true;
13
14 if (destinationType == typeof(InstanceDescriptor)) return true;
15
16 return base.CanConvertTo(context, destinationType);
17 }
18
19 public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
20 {
21 String result = "";
22 if (destinationType == typeof(String))
23 {
24 Scope scope = (Scope)value;
25 result = scope.Min.ToString()+"," + scope.Max.ToString();
26 return result;
27
28 }
29
30 if (destinationType == typeof(InstanceDescriptor))
31 {
32 ConstructorInfo ci = typeof(Scope).GetConstructor(new Type[] {typeof(Int32),typeof(Int32) });
33 Scope scope = (Scope)value;
34 return new InstanceDescriptor(ci, new object[] { scope.Min,scope.Max });
35 }
36 return base.ConvertTo(context, culture, value, destinationType);
37 }
38
39 public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
40 {
41 if (value is string)
42 {
43 String[] v = ((String)value).Split(',');
44 if (v.GetLength(0) != 2)
45 {
46 throw new ArgumentException("Invalid parameter format");
47 }
48
49 Scope csf = new Scope();
50 csf.Min = Convert.ToInt32(v[0]);
51 csf.Max = Convert.ToInt32(v[1]);
52 return csf;
53 }
54 return base.ConvertFrom(context, culture, value);
55 }
56
57 public override bool GetPropertiesSupported(ITypeDescriptorContext context)
58 {
59 return true;
60 }
61
62 public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
63 {
64 return TypeDescriptor.GetProperties(typeof(Scope), attributes);
65 }
66 }

  在GetProperties方法里,我用TypeDescriptor获得了Scope类的所有的属性描述器并返回。如果你对TypeDescriptor还不熟悉的话,可以参考MSDN。
重写这两个方法并编译以后,在测试工程里查看控件的属性,你可以看到Scope是如下的形式: