[C#]自訂元件屬性設定Form
我們一般在設計UserControl時都會幫這些UserControl開許多屬性以供彈性化設計,但我們如何做到像以下Font屬性,按下按鈕後會跳出一個字型設定畫面呢?
以下簡單描述一下我們自訂的屬性如何實現以上的設定模式。
首先我們先new一個Class,用來實作我們所需要的UITypeEditor,程式碼如下,請注意我標示為****的部分,預計在按下屬性設定時會出現Form3:
01
using System;
02
using System.Collections.Generic;
03
using System.ComponentModel;
04
using System.ComponentModel.Design;
05
using System.Drawing;
06
using System.Drawing.Design;
07
using System.IO;
08
using System.Text;
09
using System.Windows.Forms;
10
using System.Windows.Forms.Design;
11
using CRMBOM;
12
13
namespace CustomControlForm
14
{
15
/// <summary>
16
/// 自訂跳出的屬性設定頁面
17
/// </summary>
18
public class MyTypeEditor : UITypeEditor
19
{
20
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
21
{
22
if (context == null || context.Instance == null)
23
return base.GetEditStyle(context);
24
return UITypeEditorEditStyle.Modal;
25
}
26
27
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
28
{
29
IWindowsFormsEditorService editorService;
30
31
if (context == null || context.Instance == null || provider == null)
32
return value;
33
34
try
35
{
36
//取得Editor的服務
37
editorService = (IWindowsFormsEditorService)
38
provider.GetService(typeof(IWindowsFormsEditorService));
39
40
//***這邊呼叫您自己的Form***
41
Form3 tForm = new Form3();
42
using (tForm)
43
{
44
tForm.ShowDialog();
45
}
46
47
return null;
48
49
}
50
finally
51
{
52
editorService = null;
53
}
54
}
55
}
56
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

接著新增一個UserControl,多了一個屬性叫MyForm,而對這個屬性我們指定一些額外的屬性給它,重點在於指定了Editor為MyTypeEditor:
01
using System;
02
using System.Collections.Generic;
03
using System.ComponentModel;
04
using System.Drawing;
05
using System.Data;
06
using System.Text;
07
using System.Windows.Forms;
08
using System.Drawing.Design;
09
10
namespace CustomControlForm
11
{
12
public partial class UserControl1 : UserControl
13
{
14
public UserControl1()
15
{
16
InitializeComponent();
17
}
18
19
//****這邊要指定Editor為MyTypeEditor
20
[Editor(typeof(MyTypeEditor), typeof(UITypeEditor))]
21
public string MyForm
22
{
23
get { return ""; }
24
set { ; }
25
}
26
}
27
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

建置完成後我們可以在工具箱看到我們剛剛新增的UserControl1:
將此元件拉到我們的Form1上:
然後在元件的屬性中找到MyForm,這時候可以看到MyForm這個屬性的後面確實有一個...的按鈕可以按:
按下去後會顯示我定義好的Form3,到此就大功告成囉。
參考資料一:http://winterdom.com/2006/08/acustomuitypeeditorforactivityproperties
參考資料二:深入剖析ASP.NET元件設計(http://findbook.tw/book/9789864215430/price)
![]() |
游舒帆 (gipi) 探索原力Co-founder,曾任TutorABC協理與鼎新電腦總監,並曾獲選兩屆微軟最有價值專家 ( MVP ),離開職場後創辦探索原力,致力於協助青少年培養面對未來的能力。認為教育與組織育才其實息息相關,都是在為未來儲備能量,2018年起成立為期一年的專題課程《職涯躍升的關鍵24堂課》,為培養台灣未來的領袖而努力。 |