创建多个扩展控件



我创建了一个继承标准WPFTextBox的扩展TextBox,我现在要做的是创建其他扩展控件类型,如TextBlockListBoxComboBox等。所有控件都具有相同的依赖项属性,如下所示,因此我正在尝试找到一种方法来实现这一点,而无需重复每个新扩展控件背后的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" />

最新更新