gpt4 book ai didi

wpf - INotifyPropertyChanged 不会导致此代码中的屏幕更新

转载 作者:行者123 更新时间:2023-12-02 14:10:07 25 4
gpt4 key购买 nike

下面的代码基于此 post :

我的问题:在这个简单的示例中,我看不出我做错了什么来让 INotifyPropertyChanged 导致 textBox1 绑定(bind)自动反射(reflect)更改。

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>

隐藏代码

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

View 模型

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

除了我犯的任何错误之外,对于任何可以通过最佳实践改进的书面内容的任何其他评论,请提出建议;例如声明 ViewModel 或设置 StaticResource。我现在正在同时学习WPF和MVVM。

最佳答案

您没有将数据上下文设置为正确的ViewModel

DataContext = New ViewModel() 

应该是:

DataContext = vm

关于wpf - INotifyPropertyChanged 不会导致此代码中的屏幕更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com