下面的代码是基于关闭此的帖子:
我的问题:我无法看到我做错了什么让INotifyPropertyChanged导致textBox1绑定自动反映这个简单示例中的更改.
XAML.我添加了textBox2来确认属性正在改变
<StackPanel>
<Button Margin="25" Content="Change the Value" Click="Button_Click"/>
<Label Content="{}{Binding MyTextProperty}"/>
<TextBox Name="textBox1" Text="{Binding MyTextProperty}"/>
<Label Content="updated using code behind"/>
<TextBox Name="textBox2" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
代码隐藏
Partial Class MainWindow
Private vm = New ViewModel
Sub New()
InitializeComponent()
DataContext = New ViewModel()
textBox2.Text = vm.MyTextProperty
End Sub
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
vm.ChangeTextValue()
textBox2.Text = vm.MyTextProperty
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
视图模型
Public Class ViewModel
Implements INotifyPropertyChanged
Private _MyTextValue As String = String.Empty
Public Property MyTextProperty() As String
Get
Return _MyTextValue
End Get
Set(ByVal value As String)
_MyTextValue = value
NotifyPropertyChanged("MyTextProperty")
End Set
End Property
Public Sub New()
MyTextProperty = "Value 0"
End Sub
Public Sub ChangeTextValue()
MyTextProperty = Split(MyTextProperty)(0) & " " & Split(MyTextProperty)(1) + 1
End Sub
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
除了我正在做的任何错误,任何其他关于任何可以通过最佳实践改进的书面评论,请指教; 例如声明ViewModel或设置StaticResource.我现在正在学习WPF和MVVM.
您没有将数据上下文设置为正确 ViewModel
DataContext = New ViewModel()
Run Code Online (Sandbox Code Playgroud)
应该:
DataContext = vm
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
119 次 |
最近记录: |