创建多个扩展控件
Creating Multiple Extended Controls
我创建了一个继承标准 WPF TextBox
的扩展 TextBox
,我现在要做的是创建其他扩展控件类型,例如 TextBlock
、ListBox
、ComboBox
等。所有控件都将具有相同的 DependencyProperties,如下所示,因此我试图找到一种方法来实现这一点,而无需重复每个新扩展控件背后的 DependencyProperty
代码。
Public Class ExtendedTextBox
Inherits TextBox
Public Shared MandatoryProperty As DependencyProperty = DependencyProperty.Register("Mandatory", GetType(Boolean), GetType(ExtendedTextBox))
Public Shared ReadOnly HasAnyErrorsProperty As DependencyProperty = DependencyProperty.Register("HasAnyErrors", GetType(Boolean), GetType(ExtendedTextBox))
End Class
您可以定义可以在任何 UIElement
:
上设置的 attached properties
Public Class MyProperties
Public Shared ReadOnly MandatoryProperty As DependencyProperty = DependencyProperty.RegisterAttached("Mandatory", GetType(Boolean), GetType(MyProperties))
Public Shared Sub SetMandatory(ByVal element As UIElement, ByVal value As Boolean)
element.SetValue(MandatoryProperty, value)
End Sub
Public Shared Function GetMandatory(ByVal element As UIElement) As Boolean
Return CType(element.GetValue(MandatoryProperty), Boolean)
End Function
End Class
XAML:
<TextBox local:MyProperties.Mandatory="True" />
<ListBox local:MyProperties.Mandatory="False" />
我创建了一个继承标准 WPF TextBox
的扩展 TextBox
,我现在要做的是创建其他扩展控件类型,例如 TextBlock
、ListBox
、ComboBox
等。所有控件都将具有相同的 DependencyProperties,如下所示,因此我试图找到一种方法来实现这一点,而无需重复每个新扩展控件背后的 DependencyProperty
代码。
Public Class ExtendedTextBox
Inherits TextBox
Public Shared MandatoryProperty As DependencyProperty = DependencyProperty.Register("Mandatory", GetType(Boolean), GetType(ExtendedTextBox))
Public Shared ReadOnly HasAnyErrorsProperty As DependencyProperty = DependencyProperty.Register("HasAnyErrors", GetType(Boolean), GetType(ExtendedTextBox))
End Class
您可以定义可以在任何 UIElement
:
Public Class MyProperties
Public Shared ReadOnly MandatoryProperty As DependencyProperty = DependencyProperty.RegisterAttached("Mandatory", GetType(Boolean), GetType(MyProperties))
Public Shared Sub SetMandatory(ByVal element As UIElement, ByVal value As Boolean)
element.SetValue(MandatoryProperty, value)
End Sub
Public Shared Function GetMandatory(ByVal element As UIElement) As Boolean
Return CType(element.GetValue(MandatoryProperty), Boolean)
End Function
End Class
XAML:
<TextBox local:MyProperties.Mandatory="True" />
<ListBox local:MyProperties.Mandatory="False" />