使用MVVM模式设计需要BackgroundAgent的应用程序的最佳实践

时间:2013-12-02 17:00:05

标签: c# xaml mvvm windows-phone-8 caliburn.micro

虽然标题看起来过于宽泛,但实际上我没有找到任何关于如何解决这个问题的提示。


编辑: 虽然我正确地标记了问题,但我忘了写我正在使用 Caliburn.Micro ,这意味着我 必须 同时拥有在同一个项目中查看 ViewModels ,这迫使我为模型创建一个单独的库项目,作为后台代理 em>不能依赖应用程序的项目


在深入研究这个问题之前,这里有一个小例子:

- App Solution
\- Model (C# library)
\- Background agent
\- Real App
  \- Views
  \- ViewModels
  \- Resources and other stuff

其中 Real App 后台代理依赖于 Model

在我看来,这是在我的方案中使事情有效的最简单方法。

当我需要使用绑定时,问题就出现了。在我以前的项目中,我曾经将 Model ViewModel 类合并为一个,这样我就可以将XAML绑定到 VIewModel 了没有任何问题的属性。

但现在,因为我被迫将 Model 保留在一个单独的项目中(后台代理不能依赖于 Real App ),我不知道这应该如何运作。

为了使事情变得更复杂,我的模型使用异步模式来加载数据。

这导致了第一个问题:由于模型使用异步模式加载数据,如何通知 ViewModel 数据准备好了吗?

为了使问题更加清晰,以下是关于此问题的快速摘录:

namespace Models
{
    public class Model
    {
        private string _neededProperty;
        public string NeededProperty
        {
            get
            {
                return _neededProperty;
            }
            set
            {
                if (value == _neededProperty) return;
                _neededProperty = value;
                OnPropertyChanged();
            }
        }

        public Model()
        {
            LoadData();
        }

        private async void LoadData()
        {
            NeededProperty = await StuffLoader();
        }

        private Task<string> StuffLoader()
        {
            return LoadStringAsync();
        }
    }
}

namespace ViewModels
{
    public class ViewModel
    {       
        public string NeededProperty
        {
            get
            {
                // Let's assume that we have a global instance of our model defined in the App.xaml.cs file
                return App.Model.NeededProperty;
            }
        }
    }
}

// Page.xaml
...
    <TextBlock Text="{Binding NeededProperty, Source={StaticResource ViewModel}}"/>
...

如果模型加载了字符串,我怎么能确定TextBlock加载好?

当然,需要解决同样的问题才能使后台代理工作,因为它依赖于模型的相同加载方法。

所以,基本上,问题是:只要我的结构正确并且这是组织项目的最佳方式,我如何“监听” Model 的属性来报告每个更改为 ViewModel 后台代理

这对于显示某种加载屏幕也很有用,必须在 Real App 部分中显示,因此我需要知道 Model 的实际时间完成装载程序。

我希望这个问题很明确,我现在有点困惑,因为这需要一个来自Java的大范式转换!

1 个答案:

答案 0 :(得分:0)

ViewModel不应与Views在同一个项目中。 这样,如果需要,您可以在不同的应用程序中重复使用Model和ViewModel(例如:桌面和手机应用程序)。 因此,我会在viewmodel中使用你的后台代理(也许可以通过模型取决于你正在做的事情)。这样,应用程序就无法知道后台代理,您的应用程序使用ViewModel的方式与使用或不使用ViewModel的方式相同

IMO是最干净,最简单的方式。