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