自訂群組件之屬性(Property)的性質(Attribute)介紹(二)
來源:互聯網
上載者:User
一:屬性轉換器(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; }
}
編譯之後的程式畫面如下