WPF用户控件中的数据绑定

时间:2012-09-26 14:10:13

标签: c# wpf vb.net data-binding user-controls

一个看似简单的问题,让我陷入僵局。我有一个包含TextBlock的usercontrol。 我希望绑定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#中的评论。感谢。

0 个答案:

没有答案