正确使视图模型失效的正确方法

时间:2019-05-23 19:47:47

标签: c# wpf viewmodel

经过一些研究,我还没有找到使视图模型数据按时失效和重新加载的解决方案。

想象一下一个具有视图模型的应用程序,该应用程序在初始化时会充满来自服务器的数据,并在一段时间(例如1分钟)后使该数据无效并再次从服务器重新加载。

正如我所假设的那样,在视图模型本身中创建调度程序计时器不是一个好主意,因为在我看来,视图模型应该负责这种事情是不对的。

this中,视频作者演示了如何在视图模型中创建调度程序计时器,以在一段时间后更新某些数据。那是VB.NET,但看起来与我要尝试的东西非常相似。

我现在看到的是在视图模型中使用调度程序:

    // ...
    public class Foo
    {
        public string Bar { get; set; }
        public int Baz { get; set; }

        // ...
    }

    // ...
    public interface IDataService
    {
        Task<Foo> GetDataAsync();
    }

    public class FooViewModel : INotifyPropertyChanged
    {
        private string _bar;
        public string Bar
        {
            get
            {
                return _bar;
            }
            set
            {
                _bar = value;
                OnPropertyChanged(nameof(Bar));
            }
        }

        private int _baz;
        public int Baz
        {
            get
            {
                return _baz;
            }
            set
            {
                _baz = value;
                OnPropertyChanged(nameof(Baz));
            }
        }

        IDataService service;
        DispatcherTimer dispatcherTimer;

        private async void dispatcherTimer_Tick(object sender, EventArgs eventArgs)
        {
            await InvalidateAndReloadDataAsync();
        }

        private void InitializeDispatcher()
        {
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 1, 0);
            dispatcherTimer.Start();
        }

        public async Task InvalidateAndReloadDataAsync()
        {
            Foo foo = await service.GetDataAsync();
            Bar = foo.Bar;
            Baz = foo.Baz;
        }

        public FooViewModel(IDataService dataService)
        {
            service = dataService;
            InitializeDispatcher();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName()] string name = null)
        {
            if (name != null) PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        // ...

    }

在视图模型中实际使用调度程序是否正常,或者有更好的解决方案?

0 个答案:

没有答案
相关问题