tags:

views:

25

answers:

2

I'm new to MVVM.

I have a label in my view that looks like this:

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

And my ViewModel looks like:

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

My problem is that the label doesn't update dynamically with the thread in the ViewModel. Is there a simple way to let the View know this value is dynamic?

+4  A: 

You need to implement the INotifyPropertyChanged interface in your ViewModel, and raise the PropertyChanged event when you set ClockTime

Todd Benning
+2  A: 

To expand on what Todd said you should update your code like this you need ViewModelBase to look something like this

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

and then modify your view model like so:

  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

Notice that i'm assigning to ClockTime and when that gets set WPF is notified that ClockTime has changed

Jose