1

一个看似简单的问题让我陷入了僵局。我有一个包含 TextBlock 的用户控件。我希望绑定 TextBlock 的几个属性(Text、FontSize、Foreground、Background、Margin)。我在想,与其创建一大堆代码和 5 个 DependencyProperties,不如简单地为这些属性创建一个小类并简单地注册它。

这是我在 UserControl.xaml 中的内容

<TextBlock Grid.Row="1" Grid.RowSpan="1" DataContext="XTitle"
                   Text="{Binding ElementName=MultiButton, Path=XTitle.Text, FallbackValue='Heart-Rate'}" 
                   FontSize="{Binding ElementName=MultiButton, Path=XTitle.FontSize, FallbackValue='26'}" 
                   Foreground="{Binding ElementName=MultiButton, Path=XTitle.ForeColor, FallbackValue='White'}" 
                   Background="{Binding ElementName=MultiButton, Path=XTitle.Background, FallbackValue='Black'}" 
                   TextAlignment="Center" VerticalAlignment="Center" />

在 (userControl.xaml.vb) 后面的代码中,我有这个:

    Public Shared ReadOnly XTitleProperty As DependencyProperty

    Shared Sub New()
        XTitleProperty = DependencyProperty.Register("XTitle", GetType(TextPart), GetType(MultiButton))
    End Sub

    Public Property XTitle As TextPart
        Get
            Return CType(GetValue(XTitleProperty), TextPart)
        End Get
        Set(value As TextPart)
            SetValue(XTitleProperty, value)
        End Set
    End Property

    Public Class TextPart
        Property Text As String = "ABCD"
        Property FontSize As Single = 16
        Property Foreground As Color = Colors.Yellow
        Property Background As Color = Colors.Black
    End Class

在 Window.xaml 中(我只是想让这一切正常工作,因此暂时没有 MVVM):

<Grid>
    <lbUserControl:MultiButton XTitle="{Binding SensorTitle}"/>
</Grid>

最后在 Window.xaml.vb 代码隐藏中,我们有这个:

    Private _sensorTitle As MultiButton.TextPart

    Public ReadOnly Property SensorTitle() As MultiButton.TextPart
        Get
            Return _sensorTitle
        End Get

    End Property

    Public Sub New()
        _sensorTitle = New MultiButton.TextPart
        _sensorTitle.Text = "HRM"
        _sensorTitle.FontSize = 16
        _sensorTitle.Foreground = Colors.Cyan
        _sensorTitle.Background = Colors.SaddleBrown
    End Sub

我显然在某个地方错过了一个技巧,因为我认为数据绑定根本没有参与。很高兴收到 vb 或 c# 中的评论。谢谢。

4

0 回答 0