一:屬性轉換器(TypeConverter)
1、 下拉列表框的形式:
要使用下拉列表框的形式的屬性我們首先要定義一個屬性,在這個例子中我定義了一個字符串類型的屬性 FileName。
private string _fileName;
public string FileName
{
get { return this._fileName;}
set { this._fileName=value; }
}
定義完屬性之后,我們還要自己一個屬性轉換器。那么什么是屬性轉換器呢?其實在屬性瀏覽器中只能夠識別字符串類型,所以我們要通過屬性轉換器把我們的屬性轉換成字符串,還要在屬性瀏覽器改變這個字符串之后在把這個字符串轉換成我們自己的屬性。大家聽起來是不是有一些胡涂了?沒關系下面我們做一個屬性轉換器大家就知道了。
因為在本例中用的屬性是字符串類型的所以我們要從System.ComponentModel.StringConverter繼承一個新的字符串形式的屬性轉換器。下面就是這段代碼和代碼中的注釋,相信大家一定能夠看懂的:
/// <summary>
/// 擴展字符串的轉換器(實現下拉列表框的樣式)
/// </summary>
public class FileNameConverter:System.ComponentModel.StringConverter
{
/// <summary>
/// 根據返回值確定是否支持下拉框的形式
/// </summary>
/// <returns>
/// true: 下來框的形式
/// false: 普通文本編輯的形式
/// </returns>
public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
{
return true;
}
/// <summary>
/// 下拉框中具體的內容
/// </summary>
public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context)
{
return new StandardValuesCollection(new string[]{"File1.bat","File2.exe","File3.dll"});
}
/// <summary>
/// 根據返回值確定是否是不可編輯的文本框
/// </summary>
/// <returns>
/// true: 文本框不可以編輯
/// flase: 文本框可以編輯
/// </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; }
}
編譯之后的程序畫面如下
|