Caliburn Micro - 使用ShellViewModel中运行的BackgroudTask中的数据更新UI

时间:2015-03-09 21:37:23

标签: c# wpf xaml caliburn.micro

我有8个视图的WPF应用程序,其中一个视图是显示在ShellViewModel.cs中每1小时运行一次的BackgroundTask的活动。

我在App.xaml.cs中创建了一个全局变量来存储每个进度的BackgroundTask状态。

public partial class App : Application
{
    public static string RunStatus { get; set; }
}

在ActivityViewModel.cs中,我创建了一个公共变量(RunStatus)并将其绑定到XAML中的Label。

刷新View时,我看到了更新的RunStatus(在UI中)。

public class ActivityViewModel : Screen
{
    public string RunStatus
    {
        get;
        set{ NotifyOfPropertyChange(() => RunStatus); }
    }

    public ActivityViewModel()
    {
        RunStatus = App.RunStatus;
    }
}

当App.RunStatus中的值发生更改而不刷新视图时,有没有办法使用NotifyOfPropertyChange()来更新具有App.RunStatus值的UI?

1 个答案:

答案 0 :(得分:-1)

您需要更新string RunStatus主题上的UI

一种方法是使用Dispatcher,Caliburn为其提供IDispatcher。

    public class ActivityViewModel : Screen
    {
        private string _runStatus;

        public string RunStatus
        {
            get {return _runStatus}
            set
            {
                _runStatus = value;
                NotifyOfPropertyChange(() => RunStatus);
            }
        }

        public ActivityViewModel(IDispatcher dispatcher)
        {
            dispatcher.BeginExecuteOnUIThread(() =>
            {
                RunStatus = App.RunStatus;
            });
        }
    }
}

或者

    public class ActivityViewModel : Screen
    {
        private readonly IDispatcher _dispatcher;
        private string _runStatus;

        public string RunStatus
        {
            get {return _runStatus}
            set
            {
                _dispatcher.BeginExecuteOnUIThread(() =>
                {
                    _runStatus = value;
                    NotifyOfPropertyChange(() => RunStatus);
                });
            }
        }

        public ActivityViewModel(IDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }

        public void SomeOtherMethod()
        {
            RunStatus = App.RunStatus;
        }
    }