【问题标题】:Update property on mainwindow even if a new window is opened in WPF即使在 WPF 中打开了新窗口,也更新主窗口上的属性
【发布时间】:2023-03-10 05:07:01
【问题描述】:

我的应用程序的主窗口上有一个属性,该属性由在后台运行的函数 (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...";
    }

【问题讨论】:

  • 您需要使用Dispatcher.CurrentDispatcher.Invoke(() => { this.CurrentData = "";}); 在此处查看有关调度程序的信息:stackoverflow.com/questions/1644079/…
  • 所有的 Windows 都使用相同的 ViewModel 吗?
  • 顺便说一句。你在哪里打电话worker.RunWorkerAsync()?它是丢失还是只是未包含在您的示例中?
  • 我猜你没有启动你的工人。否则,在从后台线程更新 UI 线程上的属性时会出现一些异常。 => 查看第一条评论!
  • 我的窗口使用相同的 ViewModel,但是当我返回主窗口时,总是会打开一个新的 viewmodel 实例。如何为视图模型创建单例类?

标签: c# wpf mvvm backgroundworker


【解决方案1】:

您可以像这样为您的 ViewModel 创建一个单例:

将此添加到您的 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。只有当每个窗口都需要相同的属性(绑定)和东西时,您才应该这样做。

否则我强烈建议每个窗口使用不同的 ViewModel。

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 2023-01-12
    • 2015-04-15
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多