實例詳解在C#中創建自定義控件的屬性和屬性集合


在自定義的控件中,通常需要自定義屬性(不然的話為什么要自定義控件)

在自定義控件中包含了多個相同類型的對象時,就會用到屬性集合

一、首先說一下屬性的定義

1、在自定義控件的類代碼中創建一個變量(可以是任何類型根據設計需要)

private bool mvalue = false;

2、創建變量對應的屬性,在屬性上添加黑體部分(屬性特性)
[Category("數據"), Description("變量值"), Browsable(true)]
public bool MValue

{

get {return mvalue;} 

set {mvalue=value}

}

Category:調用控件時屬性的分組(下圖:1)

Description:選中該屬性時的提示信息,可用於描述屬性任何設置和使用(下圖:2)

Browsable:是否在屬性欄中顯示該屬性

屬性可定義的特性很多,最常用的就是上述3個

創建好屬性后生成一下就可以在窗體設計器的工具欄中看到並調用自定義的控件,選中控件和就在屬性欄中看到下圖中的效果

 

二、屬性集合定義

上面已經說過使用屬性集合,是因為自定義的控件中有多相同的對象需要在調用時進行設置。(當然你要說是為了把多個屬性放在一起好找也不是不行)

下面用兩個例子來說明

例1:控件中用到多個圖形對象(前景、背景、標志.......)

1、創建一個類用來封裝調用控件后添加圖片對象時需要設置的屬性

public class BsItem : Component
{
private Image _imageItem;
[Description("選中圖片"), Category("外觀")]
public Image SelectImage { get { return _imageItem; } }

private string _ImageName;
[Description("圖片路徑"), Category("外觀")]
public string ImageName
{
get { return _ImageName; }
set
{
_ImageName = value;
this._imageItem = Image.FromFile(_ImageName);
_ImageName = System.IO.Path.GetFileName(_ImageName);
Name = _ImageName;
}
}

2、定義一個圖片集合

private List<BsItem> items = new List<BsItem>();
[TypeConverter(typeof(System.ComponentModel.CollectionConverter))]//指定編輯器特性
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]//設定序列化特性
[Category("外觀"), Description("圖像文件集")]
public List<BsItem> ImageList
{
get { return items; }
}

 

[Browsable(false)]//不顯示Name 屬性
public string Name { get; set; }
}

 調用時的效果圖

 

例2:控件中用到多個自定義變量,需要在調用時設置:數據來源、不同狀態下顯示的內容等屬性

屬性中包含了BOOL,string,圖形,枚舉,自定義等多種數據類型

方法與例1相同,這些屬性的具體使用代碼不贅述,只要在{ get; set; }中編寫就OK了

private List<DataAttribute> mDataAttribute = new List<DataAttribute>();
[TypeConverter(typeof(System.ComponentModel.CollectionConverter))]//指定類型裝換器
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Category("外觀"), Description("圖像文件集")]
public List<DataAttribute> MDataAttribut
{
get { return mDataAttribute; }
set { mDataAttribute = value; }
}
public class DataAttribute
{
[Description("變量名稱"), Browsable(true)]
public string VariableName { get; set; }

[Description("允許讀取變量值"), Browsable(true)]
public bool ReadEnabled { get; set; }

[Description("變量存儲區"), Browsable(true)]
public catalogOne CatalogOneName { get; set; }

[Description("全局數據塊號,DB1對應用戶程序的最小全局DB塊"), Browsable(true)]
public catalogTwo CatalogTwoName { get; set; }

[Description("變量為1時顯示的圖片"), Browsable(true)]
public Image TrueImage { get; set; }

[Description("變量為0時顯示的圖片"), Browsable(true)]
public Image FalseImaRge { get; set; }

[Description("變量未加載時顯示的圖片"), Browsable(true)]
public Image NotImage { get; set; }

}

效果圖



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM