我有一个文本框和一个按钮。按钮命令应该更改绑定(bind)到文本框的属性。
但是我在命令执行后看不到任何视觉变化。
我认为与 wpf 绑定(bind)有关的简单问题
请帮我解决这个问题
应用来源:
<UserControl.DataContext>
<local:SampleViewModel />
</UserControl.DataContext>
<Grid>
<StackPanel>
<TextBox Height="23" Width="120" Text="{Binding MyName}" />
<Button Content="Click" Command="{Binding ButtonCommand}" />
</StackPanel>
</Grid>
查看型号:
Private _myName As String
Public Property MyName As String
Get
Return _myName
End Get
Set(value As String)
_myName = value
OnPropertyChanged("MyName")
End Set
End Property
Public _buttonCommand As DelegateCommand
Public ReadOnly Property ButtonCommand As DelegateCommand
Get
Return If(_buttonCommand IsNot Nothing, _buttonCommand,
New DelegateCommand(AddressOf Execute, AddressOf CanExecute))
End Get
End Property
Private Sub Execute()
MyName = "Executed"
End Sub
Private Function CanExecute() As Boolean
Return True
End Function
Public Event PropertyChanged As PropertyChangedEventHandler
Private Sub OnPropertyChanged(propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
最佳答案
请执行下列操作:
1.
类主窗口
实现 INotifyPropertyChanged
2.在 Public Sub New() 中确保你写 Me.DataContext = Me
设置数据上下文
备注 :如果您使用 ViewModel 并在 XAML 中设置,请忽略第 2 步
3.像这样修改 ProperyChanged:
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
仅在 implementing INotifyPropertyChanged
correctly 之后在 PropertyChanged 事件之后,Binding 是否会正确刷新 MyName 属性
关于wpf - 简单的 MVVM 绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12917713/