2012-06-21 92 views
2

我已经创建了一个wpf vb.net项目并且正在尝试设置一个简单的数据绑定。我不确定如何设置我的DataContext = this;在codebind中。目前,当我运行程序时,我的标签永远不会更新。我在下面列出了我的代码。我错过了什么?如何将一个属性绑定到Wpf中的文本框

<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 

回答

3

这是近 - 你需要命名的XAML您的标签(这样就可以从代码中引用它的后面),然后绑定对象到你想绑定的数据中指定的路径。

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

,然后在你的代码,你需要在标签的DataContext设置到对象你:在这种情况下,您将看到一个Name属性,其内容要分配给标签文本被绑定的对象想拥有它绑定到,在这种情况下,一个特定的实例,类PersonsomePerson

Private somePerson As New Person 

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

感谢Ĵ..,我想到了我的码了一点,所有我需要是被立为我的DataContext对人。就像你会做一个viewModel一样。这使我无需命名我的任何控件。我感谢你的回应。 – poco

+0

@poco - 将你的类DataContext设置为'person'的作品,但它是一个相当有限的方法。这意味着你班上的所有绑定都会看到“人”。你并不是真的想让'person'成为整个类的DataContext,只是为了那个特定的标签。你班级的其他部分可能想要其他数据上下文。我想,这取决于你在做什么,以及它可能会变得多么复杂。 –

相关问题