2

我创建了一个 wpf vb.net 项目,并试图设置一个简单的数据。我不确定如何设置我的 DataContext = this; 在代码绑定中。目前,当我运行程序时,我的标签永远不会更新。我在下面包含了我的代码。我错过了什么?

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="{Binding person.Name}"/>
    </Grid>
</Window>

Class MainWindow 
    Private Property person As New Person()

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        person.Name = "Poco"
    End Sub
End Class

System.ComponentModel

Public Class Person
    Implements INotifyPropertyChanged

    Private _name As String
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value

            OnPropertyChanged(New PropertyChangedEventArgs("Name"))
        End Set
    End Property

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Public Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs)
        If Not PropertyChangedEvent Is Nothing Then
            RaiseEvent PropertyChanged(Me, e)
        End If
    End Sub
End Class
4

1 回答 1

3

这很接近 - 您需要在 XAML 中命名您的标签(以便您可以从后面的代码中引用它),然后在绑定对象中指定要绑定的数据的路径。在这种情况下,您将绑定一个具有Name您希望将其内容分配给标签文本的属性的对象:

<Label Name="MyLabel" Content="{Binding Path = Name}"/>

然后在您的代码中,您需要将DataContext标签设置为您希望将其绑定到的对象,在本例somePerson中为类的特定实例Person

Private somePerson As New Person

Public Sub New()
    InitializeComponent()
    MyLabel.DataContext = somePerson
    somePerson.Name = "Poco"
End Sub
于 2012-06-21T16:16:15.590 回答