屬性編輯,正常來說不需要自定義,因為一般的屬性,在裡面都能支援,當要進行一個自定義類型的屬性編輯時,就得進行屬性編輯器的自定義了。
如何讓自己的屬性支援如

有一個下拉框按鈕呢。預設隻支援内置的類型。假如想要進行自定義就是今天的内容了。
首先我們從Msdn中的得知,有一個UITypeEditor這個基類也是一個特性。
擁有它就能夠進行屬性的自定義了
1.建立一個自定義的class
Public Class MyEditAttribute
Inherits UITypeEditor
End Class
然後重寫四個方法,GetEditStyle、EditValue、PaintValue、GetPaintValueSupported。
接下來一一講解
-
GetEditStyle
重寫該方法以指定屬性編輯右側的小按鈕是…還是下拉箭頭。這裡以下拉箭頭為例也就是UITypeEditorEditStyle.DropDown
Public Overrides Function GetEditStyle(context As System.ComponentModel.ITypeDescriptorContext) As System.Drawing.Design.UITypeEditorEditStyle
Return UITypeEditorEditStyle.DropDown
End Function
2.EditValue
指定了下拉箭頭的風格後,接下來重寫單擊下拉箭頭時會調用的函數。
Public Overrides Function EditValue(context As System.ComponentModel.ITypeDescriptorContext, provider As System.IServiceProvider, value As Object) As Object
Dim edsc As IWindowsFormsEditorService = CType(provider.GetService(GetType(IWindowsFormsEditorService)), IWindowsFormsEditorService) '聲明一個下拉窗體以容納我們接下來的控件
'這裡以清單框為例
Dim EditList As New Listbox
EditList.AddRange({"FirstValue","SecondValue"})'簡單的添加兩個值,為字元串類型,**下面标記的屬性也将是字元串類型**
if edsc IsNot Nothing then
edsc.DropDownControl(EditList) '将下拉控件設定為我們的清單框
End if
'這個函數有個傳回值,這個傳回值即是設定屬性的值。
'這裡以清單框的選項的值傳回
Return EditList.SelectedItem.tostring
End Function
3.GetPaintValueSupported,重寫這個函數的目的是讓它支援屬性框左側的繪制。如Color屬性
Public Overrides Function GetPaintValueSupported(context As System.ComponentModel.ITypeDescriptorContext) As Boolean
Return True 'true顯示左側框框,false則為不顯示
End Function
4.PaintValue,這個即是繪制左側框框的方法了,重寫它,我們就能繪制想要的了。
Public Overrides Sub PaintValue(e As System.Drawing.Design.PaintValueEventArgs)
MyBase.PaintValue(e)
e.Graphics.DrawString("test", New Font("宋體", 9), Brushes.Black, New Point(0, 0))
End Sub
這裡就繪制test文字上去吧
如圖所示,但是你會發現超出了範圍。實際上這裡的左側黑框,我們能通過e.bounds,進行擷取,這樣就可以在該範圍内進行繪制了。具體可以自己調整,不多贅述了。
這裡的所有方法重寫完畢了。
最後
自定義一個控件類
聲明一個TestPro屬性,并在上面打上屬性編輯器的标記如下
Public Class MyControl
Inherits UserControl
<EditorAttribute(GetType(MyEditAttribute), GetType(System.Drawing.Design.UITypeEditor))>
Public Property TestPro As String
End Class
然後生成後即可看到TestPro左側有繪制的文字右側有個下拉箭頭,單擊後有一個下拉清單框。具體效果,可以自行測試。
文末:
本文這次僅以下拉框為例,當然也可以以另一種風格來編輯,但是都沒多大差別,打開對話框即是以UITypeEditorEditStyle.Modal這個風格的。更多自行測試即可。