wpf - 简单的 MVVM 绑定(bind)问题

标签 wpf vb.net data-binding mvvm

我有一个文本框和一个按钮。按钮命令应该更改绑定(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/

相关文章:

VB.NET:使用结构被认为是令人讨厌的吗?

wpf - 在 MVVM 中绑定(bind) DocumentViewer

wpf - 获取 DoDragDrop DragSource

c# - 悬停 ComboBox 时更改 ComboBoxItem 的前景色

mysql - 监控MySQL表中的新数据

MVVM - 自定义模型的 MutableLiveData 没有通过数据绑定(bind)更新到 ViewModel 并且始终为空

带有集合对象的 WPF 数据绑定(bind)

c# - 使用 wpf C# Ado.Net 数据实体从 SQL Server 获取图像到数据网格中

c# - 绑定(bind)到 TabControl SelectedIndex

vb.net - 在 Visual Studio 2010 中查看设计器代码