[C#.NET][VB.NET][Winform][User Control] 自訂控制項的顯示視窗屬性 /User Control of Properties(一)
我們都知道控制項都是利用屬性觸發相關功能,我們在寫自訂控制項時一定會用到屬性,但控制項的屬性怎麼列出來呢?
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
把 IsConnected 藏起來
屬性分類
CategoryAttribute 類別 = 指定分類的名稱,該分類會在將 PropertyGrid 控制項設定為 [分類] 模式時,以群組方式來顯示屬性或事件。
C# [Category("自訂屬性")] public bool IsConnected { get; set; }
VB <[Category]("自訂屬性")> Property IsConnected As Boolean
屬性說明
DescriptionAttribute 類別 = 指定屬性或事件的描述。
C# [Description("連線與否")] public bool IsConnected { get; set; }
VB <[Description]("連線與否")> Property IsConnected As Boolean
自訂控制項圖示
請參考 [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
屬性唯讀
ReadOnlyAttribute 類別 = 指定這個屬性 (Attribute) 繫結的屬性 (Property) 在設計階段是唯讀的或是讀取/寫入的。這個類別無法被繼承。
就算屬性可以Set也是唯讀
C# [ReadOnly(true)] public bool IsConnected { get; set; }
VB <ReadOnly(true)> Property IsConnected As Boolean
指定類別遇設屬性
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
範例下載
本文转自http://www.dotblogs.com.tw/yc421206/archive/2010/06/15/15897.aspx
浙公网安备 33010602011771号