我仍然相对较新的WPF并且在绑定方面遇到困难。我试图将标签内容绑定到对象属性的属性。我尝试了几种方法,这是最新版本。在构造对象的实例时,将对属性进行更新。到目前为止,我没有在创建和分配新实例时看到更新。
班级:
Public Class TestClass
Implement INotifyPropertyChanged
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Private _name As String
Public Property Name As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
OnPropertyValueChanged()
End Set
End Property
Protected Overridable Sub OnPropertyChanged(<CallerMemberNameAttribute> Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
窗口:
Public Class MainWindow
Inherits Window
Public Property Instance As TestClass
Private Sub btnNew_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Instance = New TestClass()
End Sub
End Class
XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test Form"
Height="499"
Width="667"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Label Content="{Binding Instance.Name}" />
</Grid>
</Window>
答案 0 :(得分:1)
该属性不再更新的原因是您没有通知用户Instance
已更改。解决此问题的一种方法是在您的DependencyProperty
中创建一个MainWindow
。
Public Property Instance As TestClass
Get
Return GetValue(InstanceProperty)
End Get
Set(ByVal value As TestClass)
SetValue(InstanceProperty, value)
End Set
End Property
Public Shared ReadOnly InstanceProperty As DependencyProperty = _
DependencyProperty.Register("Instance", _
GetType(TestClass), GetType(MainWindow), _
New PropertyMetadata(Nothing))
这将取代您当前的财产。您的按钮点击代码将保持不变。 DependencyProperty
会处理通知,因此您无需明确调用OnPropertyChanged
。
另外,如果您仍在学习,可能需要查看Model-View-ViewModel(MVVM)模式,因为这似乎是常见的WPF
模式。