我的应用程序的主窗口有一个属性,由后台运行的功能(DoWork)更新。 BackgroundWorker在ViewModel中实现。如果我打开一个新页面并回到主窗口,则此属性会自动获取其在ViewModel构造函数中初始化的默认值。 即使打开了新窗口,我该怎么做才能更新此属性?
public class ImageViewModel : INotifyPropertyChanged
{
private string currentData;
public ImageViewModel()
{
img = new ImageFile { path = "" };
currentData = "There is currently no update";
this.worker = new BackgroundWorker();
this.worker.DoWork += this.DoWork;
this.worker.ProgressChanged += this.ProgressChanged;
this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_Completed);
this.worker.WorkerReportsProgress = true;
}
public string CurrentData
{
get { return this.currentData; }
private set
{
if (this.currentData != value)
{
this.currentData = value;
this.RaisePropertyChanged("CurrentData");
}
}
}
...
private void DoWork(object sender, DoWorkEventArgs e)
{
...
this.CurrentData = "file X is being updated...";
...
}
void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
this.CurrentData = "There is currently no update...";
}
答案 0 :(得分:1)
您可以像这样为ViewModel创建一个Singleton:
将其添加到ViewModel类:
public static YourViewModelType Instance { get; set; }
在Window.xaml.cs
中,然后像这样分配DataContext:
if(YourViewModel.Instance == null)
{
YourViewModel.Instance = new YourViewModelType();
}
this.DataContext = YourViewModel.Instance;
注意:强> 这将导致您的所有Windows具有相同的DataContext。只有每个Window都需要相同的属性(绑定)和东西时才应该这样做。
否则我强烈建议每个窗口使用不同的ViewModel。