2013-11-26 23 views
1

我需要适应的场景,我有像定时器的东西,并希望改变属性值反映在用户界面在一刻(基本上我需要每隔x秒更新用户界面)。如何将方法添加到ViewModel并从那里触发PropertyChanged事件?

我需要知道如何将方法添加到ViewModel并从那里触发PropertyChanged事件。

namespace MyClient.Common 
    { 
     public abstract class BindableBase : INotifyPropertyChanged 
     { 
      public event PropertyChangedEventHandler PropertyChanged; 

      protected bool SetProperty<T>(ref T storage, T value, /*[CallerMemberName]*/ String propertyName = null) 
      { 
       if (object.Equals(storage, value)) return false; 

       storage = value; 
       this.OnPropertyChanged(propertyName); 
       return true; 
      } 

      protected void OnPropertyChanged(/*[CallerMemberName]*/ string propertyName = null) 
      { 
       var eventHandler = this.PropertyChanged; 
       if (eventHandler != null) 
       { 
        eventHandler(this, new PropertyChangedEventArgs(propertyName)); 
       } 
      } 

      public void CallOnPropertyChanged() 
      { 
       // what to add here? 
      } 

     } 
    } 

App.xaml.cs

namespace MyClientWPF 
{ 
    /// <summary> 
    /// Interaction logic for App.xaml 
    /// </summary> 
    public partial class App : Application 
    { 


     private void DispatcherTimer_Tick(object sender, EventArgs e) 
     { 
      App._myDataSource.Load(); 
      App._myDataSource.CallOnPropertyChanged(); 
      // I need to rise OnPropertyChanged here 
     } 

     protected override void OnStartup(StartupEventArgs e) 
     { 


      // timer on the same thread 
      System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); 
      dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick); 
      dispatcherTimer.Interval = new TimeSpan(0, 0, 20); // 10 seconds 
      dispatcherTimer.Start(); 

      base.OnStartup(e); 
     } 



    } 
} 
+0

要通知哪些属性? – atomaras

+0

任何属性,我需要刷新所有UI – GibboK

+2

使OnPropertyChanged公开,并用空的propertyName调用它。空由WPF解释为“此对象的所有属性都已更改”。 – atomaras

回答

0

使用这样的事情在后面的代码?

((TestViewModel)this.DataContext).OnPropertyChanged("PropName"); 

您可以直接致电OnPropertyChanged();

但是,它似乎确实有一个更好的方式来完成你想要完成的任务。我宁愿尝试@emedbo的建议。

相关问题