我需要适应我有类似计时器之类的场景,并希望在某个时刻更改UI中反映的属性值(基本上我需要每隔x秒更新一次UI)。
我需要知道如何向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 :(得分:0)
在你的代码中使用这样的东西吗?
((TestViewModel)this.DataContext).OnPropertyChanged("PropName");
您可以直接致电OnPropertyChanged();
。
但似乎必须有一种更好的方式来做你想要完成的事情。我宁愿尝试@emedbo的建议。