Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 绑定到MVVM中ViewModel中更新的值?_.net_Mvvm - Fatal编程技术网

.net 绑定到MVVM中ViewModel中更新的值?

.net 绑定到MVVM中ViewModel中更新的值?,.net,mvvm,.net,Mvvm,我是MVVM的新手 我的视图中有一个标签如下所示: <Label Content="{Binding Path=ClockTime}" /> 我的问题是标签不会随ViewModel中的线程动态更新。有没有简单的方法让视图知道此值是动态的?您需要在ViewModel中实现INotifyPropertyChanged接口,并在设置时钟时间时引发PropertyChanged事件您需要在ViewModel中实现INotifyPropertyChanged接口,并在设置时钟时间时引发Pro

我是MVVM的新手

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

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

我的问题是标签不会随ViewModel中的线程动态更新。有没有简单的方法让视图知道此值是动态的?

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

您需要在ViewModel中实现INotifyPropertyChanged接口,并在设置时钟时间时引发PropertyChanged事件,以扩展Todd所说的应该像这样更新代码的内容 您需要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已更改,以扩展Todd所说的内容,您应该像这样更新代码 您需要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已更改