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
感谢Ĵ..,我想到了我的码了一点,所有我需要是被立为我的DataContext对人。就像你会做一个viewModel一样。这使我无需命名我的任何控件。我感谢你的回应。 – poco
@poco - 将你的类DataContext设置为'person'的作品,但它是一个相当有限的方法。这意味着你班上的所有绑定都会看到“人”。你并不是真的想让'person'成为整个类的DataContext,只是为了那个特定的标签。你班级的其他部分可能想要其他数据上下文。我想,这取决于你在做什么,以及它可能会变得多么复杂。 –