如何将属性数据绑定到Wpf中的文本框

时间:2012-06-21 15:59:57

标签: vb.net data-binding inotifypropertychanged

我创建了一个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

1 个答案:

答案 0 :(得分:3)

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

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

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

Private somePerson As New Person

Public Sub New()
    InitializeComponent()
    MyLabel.DataContext = somePerson
    somePerson.Name = "Poco"
End Sub