余小章 @ 大內聖殿
祕訣無它, 唯勤而已, by 余小章

导航

 

我們都知道控制項都是利用屬性觸發相關功能,我們在寫自訂控制項時一定會用到屬性,但控制項的屬性怎麼列出來呢?

2010-6-15 上午 11-07-00

System.ComponentModel 命名空間 提供相當多的類別供程式設計師使用,定義控制項的顯示方式。

在此將把我用過的類別做一個筆記

實值型別 的回傳屬性

C#
//一般屬性
private string _AppVersion = "1.0";
public string AppVersion
{
get { return _AppVersion; }
set { _AppVersion = value; }
}

VB
'一般屬性
Private _AppVersion As String = "1.0"
Public Property AppVersion() As String
Get
Return _AppVersion
End Get
Set(ByVal value As String)
_AppVersion = value
End Set
End Property
 
C#
//自動屬性,C#2008後支援

public bool IsConnected { get; set; }

VB
'自動屬性,VB2010支援

Property
IsConnected As Boolean 

 

屬性顯示與否

BrowsableAttribute 類別 = 指定屬性或事件是否應該在 [屬性] 視窗中顯示

C#
[Browsable(false)]
public bool IsConnected { get; set; }

 

VB
<[Browsable](False)>
Property IsConnected As Boolean

2010-6-15 下午 01-06-19

把 IsConnected 藏起來

屬性分類

CategoryAttribute 類別 = 指定分類的名稱,該分類會在將 PropertyGrid 控制項設定為 [分類] 模式時,以群組方式來顯示屬性或事件。

C#
[Category("自訂屬性")]
public bool IsConnected { get; set; }
VB
<[Category]("自訂屬性")>
Property IsConnected As Boolean

 

2010-6-15 下午 01-05-08

屬性說明

DescriptionAttribute 類別 = 指定屬性或事件的描述。

C#
[Description("連線與否")]
public bool IsConnected { get; set; }

 

VB
<[Description]("連線與否")>
Property IsConnected As Boolean

 

2010-6-15 下午 01-04-08

自訂控制項圖示

請參考 [C#.NET][VB.NET] 自訂控制項工具箱圖示 - ToolboxBitmap Attribute

 

屬性預設值

DefaultValueAttribute 類別 = 指定屬性的預設值。

C#
private string _AppVersion="1.0";
[Browsable(true),Category("自訂屬性"),DefaultValue("1.0")]
public string AppVersion
{
get { return _AppVersion; }
set { _AppVersion = value; }
}

 

 

VB
Private _AppVersion As String = "1.0"
<Browsable(True), Category("自訂屬性"), DefaultValue("1.0")>
Public Property AppVersion() As String
Get
Return _AppVersion
End Get
Set(ByVal value As String)
_AppVersion = value
End Set
End Property

 

2010-6-15 下午 01-15-48

屬性唯讀

ReadOnlyAttribute 類別 = 指定這個屬性 (Attribute) 繫結的屬性 (Property) 在設計階段是唯讀的或是讀取/寫入的。這個類別無法被繼承。

就算屬性可以Set也是唯讀

C#
[ReadOnly(true)]
public bool IsConnected { get; set; }
VB
<ReadOnly(true)>
Property IsConnected As Boolean
2010-6-15 下午 12-45-06

 

指定類別遇設屬性

DefaultPropertyAttribute 類別 = 指定元件的預設屬性。

載入控制項時第一個要呈現的屬性

C#
[DefaultPropertyAttribute("IsConnected")]
public partial class CSUserControl1 : UserControl
{
}
VB
<[DefaultPropertyAttribute]("IsConnected")>
Public Class VBUserControl1
End Class

下拉式屬性

首先建立一個列舉

C#
public enum StatusEnum:int
{
Normal,Advanced
}
VB
Public Enum StatusEnum As Integer
Normal
Advanced
End Enum

回傳列舉

C#
[Category("自訂屬性")]
public StatusEnum Status { get; set; }

VB
<[Category]("自訂屬性")>
Public Property Status As StatusEnum
2010-6-15 下午 01-46-06

 

範例下載

UserControls.zip

posted on 2010-07-15 15:17  余小章  阅读(2457)  评论(1编辑  收藏  举报