一個TypeConverter
並不那麼可怕,因爲它聽起來:首先,列表框屬性聲明:
Public Class ListBoxEx
Inherits ListBox
<Browsable(True), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
Public Property SelectedItemColor As ItemStateColors
<Browsable(True), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
DefaultValue(-1)>
Public Property UnSelectedItemColor As ItemStateColors
Public Sub New()
' they are Objects, be sure to instance them!
' VERY important!
SelectedItemColor = New ItemStateColors
UnSelectedItemColor = New ItemStateColors
End Sub
end class
下一個定義類:
<TypeConverter(GetType(ItemStateConverter))>
Public Class ItemStateColors
<Browsable(True), NotifyParentProperty(True),
EditorBrowsable(EditorBrowsableState.Always), DefaultValue(GetType(Color), "")>
Public Property EnabledBackColor As Color
<Browsable(True), NotifyParentProperty(True),
EditorBrowsable(EditorBrowsableState.Always), DefaultValue(GetType(Color), "")>
Public Property DisabledBackColor As Color
Public Sub New()
' default values, if any
EnabledBackColor = SystemColors.Window
DisabledBackColor = SystemColors.Control
End Sub
End Class
您的每一個ItemState
屬性是這個類的一個實例。請注意,Type
包含TypeConverter
屬性 - 這提供了「魔術」。我們將提供的expando能力和屬性網格(S)翻譯的內容顯示:
Public Class ItemStateConverter
Inherits ExpandableObjectConverter
Public Overrides Function ConvertTo(context As ITypeDescriptorContext,
culture As Globalization.CultureInfo,
value As Object, destinationType As Type) As Object
If destinationType Is GetType(String) Then
Dim item As ItemStateColors = CType(value, ItemStateColors)
' ToDo: decide the format of collapsed info
Return String.Format("{0}, {1}", item.EnabledBackColor.ToString,
item.DisabledBackColor.ToString)
End If
Return MyBase.ConvertTo(context, culture, value, destinationType)
End Function
End Class
的Component
方法更容易實現,但TypeConverter
允許您控制當財產被摺疊顯示的內容:
上述功能之一的TypeConverter,通常執行是序列化代碼/ DES爲設計師排列你的類型。這裏不需要,因爲Type只是Color
,VS/NET知道該怎麼做。它所做的在這種情況下做的是:
- 標記的財產擴展
- 提供當財產被摺疊的「摘要」信息
你會需要它的另一件事是,當你嵌入一個類型另一個(如在myControl.StateEnabled.SelectedItem.ForeColor
)。通過將它們嵌套在一起,你將需要一個TypeConverter
或者一些代碼解決方案,例如一個實例引用(並且我永遠無法知道你的問題的哪些元素是必備的)。 VS只知道鑽入第一層,您將不得不提供TypeConverter
深入查看顏色數據。然而,SelectedItem
,DeselectedItem
和ReadOnlyItem
都可以使用相同的TypeConverter
。
foo的類型不同於組分繼承,也向下提供一個空的下降。
參見:
ExpandableObjectConverter
How to: Implement a Type Converter
最後一點:所有的道具二傳手應該測試傳遞的價值和拒絕Color.Transparent
。
這不是簡單的化妝品。首先,它依賴於一個類型,你可能會將它們定義爲顏色。其次,如果Type是一個標準類型,比如Size或Point,VS會自動執行它(定義一個新的道具'FooBar As Point'並參見)。否則,您可能需要編寫自己的UITypeEditor和/或TypeConverter。 (請注意鏈接文章中的所有標準類型:位置,字體大小)。有時,您可以在TypeConverter中提供足夠的信息以使其自動工作。 – Plutonix 2014-12-09 14:06:22