创建多个扩展控件

Posted

技术标签:

【中文标题】创建多个扩展控件【英文标题】:Creating Multiple Extended Controls 【发布时间】:2018-09-19 18:58:24 【问题描述】:

我创建了一个继承标准 WPF TextBox 的扩展 TextBox,我现在要做的是创建其他扩展控件类型,例如 TextBlockListBoxComboBox 等。所有控件将具有相同的 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

【问题讨论】:

【参考方案1】:

你可以定义attached properties,可以在任何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" />

【讨论】:

以上是关于创建多个扩展控件的主要内容,如果未能解决你的问题,请参考以下文章