绑定到在MVVM中的ViewModel中更新的值?

时间:2010-07-01 15:09:26

标签: .net mvvm

我是MVVM的新手。

我的视图中有一个标签,如下所示:

<Label Content="{Binding Path=ClockTime}" />

我的ViewModel看起来像:

Public Class MainWindowViewModel
  Inherits ViewModelBase

  Dim strClockTime As String
  Dim dstDispatcherTimer As New Windows.Threading.DispatcherTimer

  Public Sub New()
    AddHandler dstDispatcherTimer.Tick, AddressOf TimeDelegate
    dstDispatcherTimer.Interval = New TimeSpan(0, 0, 1)
    dstDispatcherTimer.Start()
  End Sub

  Private Sub TimeDelegate(ByVal sender As Object, ByVal e As System.EventArgs)
    strClockTime = DateTime.Now.ToString("dddd, dd MMMM yyyy h:mm:ss tt")
  End Sub

  Public ReadOnly Property ClockTime As String
    Get
      Return strClockTime
    End Get
  End Property

End Class

我的问题是标签不会与ViewModel中的线程动态更新。是否有一种简单的方法让View知道这个值是动态的?

2 个答案:

答案 0 :(得分:4)

您需要在ViewModel中实现INotifyPropertyChanged接口,并在设置ClockTime时引发PropertyChanged事件

答案 1 :(得分:2)

要扩展托德所说的应该像这样更新你的代码 你需要ViewModelBase看起来像这样

Public class ViewModelBase Inherits INotifyPropertyChanged
  protected Sub OnPropertyChanged(PropertyName as string)
    if PropertyChanged is not nothing then
      PropertyChanged(new PropertyChangedEventArgs(PropertyName)
    end if 
  End Sub
End Class

然后修改您的视图模型:

  Private Sub TimeDelegate(ByVal sender As Object, ByVal e As System.EventArgs)
    ClockTime = DateTime.Now.ToString("dddd, dd MMMM yyyy h:mm:ss tt")
  End Sub

  Public Property ClockTime As String
    Get
      Return strClockTime
    End Get
    Private Set
      strClockTime = value
      OnPropertyChanged("ClockTime")
    End Set
  End Property

请注意,我正在分配给ClockTime,当它被设置为WPF时,会通知ClockTime已更改