wpfvb.netdependency-propertiesextended-properties

Creating Multiple Extended Controls


I have created an Extended TextBox that Inherits a standard WPF TextBox, what I am now trying to do is create other extended control types like a TextBlock, ListBox, ComboBox etc. All controls will have the same DependencyProperties as shown below so I am trying to find a way to implement this without repeating the DependencyProperty code behind each new extended control.

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

Solution

  • You could define attached properties that can be set on any 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" />