自定義組件之屬性(Property)的性質(Attribute)介紹(三)
2024-07-21 02:24:24
供稿:網友
2、展開的形式
展開的形式多用于一個屬性為我們自定義類的類型,比如我們定義了一個類,該類中的一個屬性是另一個我們定義的類。在這種情況下屬性瀏覽器默認是沒有辦法來進行類型轉換的,所以顯示為不可編輯的內容。如果我們要以展開的形式編輯這個屬性就需要我們向上面一樣來重寫屬性轉換器。
我們首先定義一個自己的類來作為以后的屬性類型。具體代碼如下:
public class expandproperty
{
private int _intlist=0;
public int intlist
{
get { return this._intlist;}
set { this._intlist=value; }
}
private string _strlist="null";
public string strlist
{
get { return this._strlist;}
set { this._strlist= value;}
}
}
然后我們在自己的另一個類中聲明一個這個類型的屬性,在這里如果我們不加任何的性質限制,屬性瀏覽器是不能轉換改屬性的。具體實現該屬性的代碼如下:
private expandproperty _droplist;
[categoryattribute("自定義的復雜類型設置(包括自定義類型轉換器)"),
typeconverterattribute(typeof(propertygridapp.expandconverter)),
readonlyattribute(false)]
public expandproperty droplist
{
get { return this._droplist;}
set { this._droplist= value;}
}
為了讓屬性瀏覽器能夠編輯該屬性,也就是說能夠把該屬性轉換成字符串,而且能夠從字符串轉換成該類的一個實例需要我們寫如下的代碼:
/// <summary>
/// 可以展開的類型轉換器
/// expandproperty
/// </summary>
public class expandconverter:system.componentmodel.expandableobjectconverter
{
public expandconverter()
{
}
/// <summary>
/// 覆蓋此方法已確定屬性是否可以轉換
/// </summary>
public override bool canconvertto(system.componentmodel.itypedescriptorcontext context, system.type destinationtype)
{
if (destinationtype==typeof(propertygridapp.expandproperty))
return true;
return base.canconvertto(context,destinationtype);
}
/// <summary>
/// 覆蓋此方法并確保destinationtype參數是一個string,然后格式化所顯示的內容
/// </summary>
public override object convertto(system.componentmodel.itypedescriptorcontext context, system.globalization.cultureinfo culture, object value, system.type destinationtype)
{
if (destinationtype == typeof (system.string) && value is propertygridapp.expandproperty)
{
propertygridapp.expandproperty source=(propertygridapp.expandproperty)value;
return source.intlist+","+source.strlist;
}
return base.convertto(context,culture,value,destinationtype);
}
/// <summary>
/// 覆蓋此方法已確定輸入的字符串是可以被轉化
/// </summary>
public override bool canconvertfrom(system.componentmodel.itypedescriptorcontext context, system.type sourcetype)
{
if (sourcetype==typeof(string))
return true;
return base.canconvertfrom(context,sourcetype);
}
/// <summary>
/// 覆蓋此方法根據 convertto() 方法的轉換格式來把所輸入的字符串轉換成類,并返回該類
/// </summary>
public override object convertfrom(system.componentmodel.itypedescriptorcontext context, system.globalization.cultureinfo culture, object value)
{
if (value is string)
{
string s=(string)value;
int comma=s.indexof(",");
if (comma!=-1)
{
try
{
string intlist=s.substring(0,comma);
string strlist=s.substring(comma+1,s.length-comma-1);
propertygridapp.expandproperty ep=new expandproperty();
ep.intlist=int.parse(intlist);
ep.strlist=strlist;
return ep;
}
catch
{
return base.convertfrom(context,culture,value);
}
}
}
return base.convertfrom(context,culture,value);
}
}
編譯之后的畫面如下:
,歡迎訪問網頁設計愛好者web開發。