PropertyGrid (上手篇)
到工具箱-> 所有控制項,拉一 PropertyGrid 控制項到 Form1 上。
程式碼片段如下:
1: Imports System.ComponentModel
2:
3: Public Class Form1
4: Sub New()
5:
6: ' 此為 Windows Form 設計工具所需的呼叫。
7: InitializeComponent()
8:
9: ' 在 InitializeComponent() 呼叫之後加入任何初始設定。
10: Dim s As New Student
11:
12: With s
13: .ID = "A00001"
14: .Name = "王小英"
15: .Sex = Student.SexType.Female
16: .Grade = 60
17: .Tel = "0939123456"
18: End With
19: PropertyGrid1.SelectedObject = s
20: End Sub
21: End Class
22:
23:
24: <DefaultProperty("ID")> _
25: Public Class Student
26:
27: Enum SexType
28: Male
29: Female
30: End Enum
31:
32: Private m_ID As String
33: Private m_Name As String
34: Private m_Sex As SexType
35: Private m_Grade As Integer
36: Private m_TEL As String
37:
38: <DisplayName("學號")> _
39: Public Property ID() As String
40: Get
41: Return m_ID
42: End Get
43: Set(ByVal value As String)
44: m_ID = value
45: End Set
46: End Property
47:
48: <Description("姓名")> _
49: Public Property Name() As String
50: Get
51: Return m_Name
52: End Get
53: Set(ByVal value As String)
54: m_Name = value
55: End Set
56: End Property
57:
58: <DefaultValue(60)> _
59: Public Property Grade() As Integer
60: Get
61: Return m_Grade
62: End Get
63: Set(ByVal value As Integer)
64: m_Grade = value
65: End Set
66: End Property
67:
68: <Browsable(False)> _
69: Public Property Tel() As String
70: Get
71: Return m_TEL
72: End Get
73: Set(ByVal value As String)
74: m_TEL = value
75: End Set
76: End Property
77:
78: Public Property Sex() As SexType
79: Get
80: Return m_Sex
81: End Get
82: Set(ByVal value As SexType)
83: m_Sex = value
84: End Set
85: End Property
86:
87: End Class
執行結果:
重點:
- 將 Student 物件指定給 PropertyGrid 控制項的 SelectedObject 屬性,就可以秀出物件的內容。
- 預設情況下,PropertyGrid 會顯示 Student 類別中所有的公開屬性。
-
在屬性上頭加上一些標籤可以有不同的效果:
- <DisplayName(“學號”)>
- <DefaultValue(60)> -----> 表示該屬性的預設值為 60,當屬性值不等於預設值時,會以粗體顯示。
- <Description(“姓名”)> -----> 該屬性的描述。
- <Browsable(“False”)> -----> 該屬性要不要顯示在 PropertyGrid 中。(不加標籤的話,Public 屬性預設會顯示)
- 屬性的資料型態若是一般的型態,如 String, Boolean, Integer, Color, Size, Font, Enum, … 則.NET 預設會有對應的編輯方式。(註:可以自訂編輯的方式,有空再提唄)
- 在 Student 類別上頭加上屬性標籤 <DefaultProperty("ID")> ------> 表示預設焦點會停在屬性 ID 那一列上。