将数据通过 XAML 传递到 VB

Passing data through XAML into VB

原始(由克莱门斯解决):

我有代码(如下),我试图通过 XAML 将参数传递到 VB。这给它一个错误代码 " 'tabText' 属性 已经被 'customTabPanel' [=27= 注册了]" 我不确定我应该在这里做什么,因为这是我第一次尝试解决这个问题

新:

这仍然无法正确传递文本,我不知道为什么。任何帮助将不胜感激。

VB:

Public Class customTabPanel
Inherits Grid
Dim workSpaceAssociation As Grid
Public ReadOnly TextProperty As DependencyProperty = DependencyProperty.Register("tabText", GetType(String), GetType(customTabPanel), New PropertyMetadata(String.Empty))
Public Property tabText() As String
    Get
        Return DirectCast(GetValue(TextProperty), String)
    End Get
    Set(value As String)
        SetValue(TextProperty, value)
    End Set
End Property
Sub New()
    Me.Height = 20
    Me.Background = New SolidColorBrush(Color.FromRgb(27, 27, 28))
    Dim textBlock As New TextBlock
    textBlock.Foreground = New SolidColorBrush(Colors.White)
    textBlock.Text = tabText
    textBlock.Width = 100
    textBlock.Padding = New Thickness(10, 0, 25, 0)
    Dim closeWorkspace As New TextBlock
    closeWorkspace.HorizontalAlignment = Windows.HorizontalAlignment.Right
    closeWorkspace.Text = ""
    closeWorkspace.Foreground = New SolidColorBrush(Colors.White)
    closeWorkspace.Height = 15
    closeWorkspace.Width = 15
    closeWorkspace.FontFamily = New FontFamily("Segoe UI Symbol")
    'add'
    Me.Children.Add(textBlock)
    Me.Children.Add(closeWorkspace)
    Me.Width = textBlock.Width
    Me.Margin = New Thickness(5, 0, 0, 0)
    Me.HorizontalAlignment = Windows.HorizontalAlignment.Left
End Sub
Sub SetText(ByVal t As String)
    tabText = t
End Sub
Function GetText() As String
    Return tabText
End Function
End Class

XAML:

<ThisIsAwsome:customTabPanel tabText="Start Screen" />

依赖项 属性 字段必须声明为 Shared:

Public Shared ReadOnly TextProperty As DependencyProperty = ...

为了获得有关更新 属性 值的通知,您还必须使用 属性 的元数据注册一个 PropertyChangedCallback:

Public Shared ReadOnly TextProperty As DependencyProperty =
    DependencyProperty.Register(
        "tabText", GetType(String), GetType(customTabPanel),
         New PropertyMetadata(
             String.Empty, New PropertyChangedCallback(AddressOf TabTextChanged)))

TabTextChanged 回调中,您将设置 TextBlock 的文本 属性(不知道它是否有效 VB):

Private Shared Sub TabTextChanged(
    ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
        Dim panel As customTabPanel = CType(d, customTabPanel)
        panel.textBlock.Text = CType(e.NewValue, String)
End Sub

您可以在 MSDN 上的 Custom Dependency Properties 文章中找到详细说明。