自定义组件之属性(Property)的性质(Attribute)介绍(二)

一:属性转换器( TypeConverter )

1、 下拉列表框的形式:

要使用下拉列表框的形式的属性我们首先要定义一个属性,在这个例子中我定义了一个字符串类型的属性 FileName 。

private string _fileName;

public string FileName

{

get { return this._fileName;}

set { this._fileName=value; }

}

定义完属性之后,我们还要自己一个属性转换器。那么什么是属性转换器呢?其实在属性浏览器中只能够识别字符串类型,所以我们要通过属性转换器把我们的属性转换成字符串,还要在属性浏览器改变这个字符串之后在把这个字符串转换成我们自己的属性。大家听起来是不是有一些胡涂了?没关系下面我们做一个属性转换器大家就知道了。

因为在本例中用的属性是字符串类型的所以我们要从 System.ComponentModel.StringConverter 继承一个新的字符串形式的属性转换器。下面就是这段代码和代码中的注释,相信大家一定能够看懂的:

///

1<summary>
2
3///  扩展字符串的转换器(实现下拉列表框的样式) 
4
5/// </summary>

public class FileNameConverter:System.ComponentModel.StringConverter

{

///

1<summary>
2
3///  根据返回值确定是否支持下拉框的形式 
4
5/// </summary>

///

1<returns>
2
3/// true:  下来框的形式 
4
5/// false:  普通文本编辑的形式 
6
7/// </returns>

public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)

{

return true;

}

///

1<summary>
2
3///  下拉框中具体的内容 
4
5/// </summary>

public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context)

{

return new StandardValuesCollection(new string[]{"File1.bat","File2.exe","File3.dll"});

}

///

1<summary>
2
3///  根据返回值确定是否是不可编辑的文本框 
4
5/// </summary>

///

1<returns>
2
3/// true:  文本框不可以编辑 
4
5/// flase:  文本框可以编辑 
6
7/// </returns>

public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context)

{

return true;

}

好了,属性转换器写完了,最后别忘了把这个属性转换器指定到我们刚才所写的属性上哦,代码如下:

[CategoryAttribute(" 自定义的复杂类型设置 ( 包括自定义类型转换器 )"),

TypeConverterAttribute(typeof(PropertyGridApp.FileNameConverter)),

ReadOnlyAttribute(false)]

public string FileName

{

get { return this._fileName;}

set { this._fileName=value; }

}

编译之后的程序画面如下:

Published At
Categories with Web编程
Tagged with
comments powered by Disqus