MVVM视图模型和异步数据初始化

Ros*_*gan 7 design-patterns mvvm mvvm-light windows-phone-8 windows-store-apps

我有一个带有需要服务的构造函数的视图模型.我正在使用GalaSoft的MvvmLight,它使用服务定位器将视图连接到视图模型.

SimpleIOC处理为viewmodels构造函数提供服务很好,但我不知何故需要使用来自数据源的数据填充我的viewmodel.我的Viewmodel看起来像这样: -

    public class MainPageViewModel : ViewModelBase
{
    private readonly GroupService _groupService;
    private readonly GroupFactory _groupFactory;
    private readonly ObservableCollection<GroupVM> _groupVms = new ObservableCollection<GroupVM>();


    public MainPageViewModel(Domain.Services.GroupService groupService, VMFactories.GroupFactory groupFactory)
    {
        _groupService = groupService;
        _groupFactory = groupFactory;
    }

    public async Task Init()
    {
        var groups = await _groupService.LoadGroups();
        foreach (var group in groups)
        {
            GroupVms.Add(_groupFactory.Create(group));
        }
    }

    public ObservableCollection<GroupVM> GroupVms { get { return _groupVms; } }
}
Run Code Online (Sandbox Code Playgroud)

不知何故,init方法需要被称为等待,但我不知道如何最好地做到这一点?我可以想到三个选择: -

  1. 我只是在构造函数上调用Init,但没有等待它(我知道这真的很糟糕)
  2. 我在ViewModelLocator对象上调用Init,但由于我无法返回任务,我再次无法等待init
  3. 在视图的加载上,我将DataContext转换为某种IAsyncViewmodel并等待init方法.

我在以前的Windows 8商店项目中使用了选项3,但它感觉不对.任何建议都会非常感激!

谢谢

罗斯

LBu*_*ion 7

我很好奇为什么你认为不等待异步调用是一种不好的做法.在我看来,只要你知道这意味着什么,调用将在后台执行并且可能随时返回,这也不错.

通常我所做的是我在构造函数中调用async方法来设计时间数据创建目的,我不等待它.我只需要处理需要更新绑定所需的PropertyChanged和CollectionChanged事件,这样就可以了.

干杯洛朗