Windows Phone 8 - MVVM ViewModels and App.xaml.cs

自闭症网瘾萝莉.ら 提交于 2019-12-07 00:28:36

问题


I've been studying the MVVM pattern and putting it into practice in a Windows Phone 8 app, and I have a question about the best practices for initializing and accessing ViewModels in an app.

When I create a Databound Application from the WP8 SDKs templates, I noticed this code in the App.xaml.cs file:

public static MainViewModel ViewModel
{
    get
    {
        // Delay creation of the view model until necessary
        if (viewModel == null)
            viewModel = new MainViewModel();

            return viewModel;
    }
}

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    // Ensure that application state is restored appropriately
    if (!App.ViewModel.IsDataLoaded)
    {
        App.ViewModel.LoadData();
    }
}

From what I understand, that means that the App class contains the MainViewModel as a static member, and when the application is activated, the ViewModel is loaded.

That being the case, I have the following questions:

  1. If my App has several ViewModels, would all of them be stored as members inside the App.xaml.cs file?

  2. If every ViewModel's data is loaded at the same time, how do I manage my app's memory? Is it possible to unload each ViewModel's data and only load the ViewModel that is being used by my View?


回答1:


There are many different approaches to instantiate ViewModels. Some of them will instantiate all at launch, while other don't instantiate the ViewModel until it is needed.

In the following blog post you will find some possible approaches to instantiate a ViewModel:

MVVM Instantiation Approaches

Answering your questions; 1.- Following your approach you would have to define members for all of your ViewModels in your App.xaml.cs file. 2.- You can follow an approach that doesn't instantiate the ViewModel until it is needed.

There exist some toolkits, such MVVM Light or Caliburn Micro, that ease the implementation of MVVM pattern. I personally use MVVM Light Toolkit, which uses the Locator approach. Using this toolkit, ViewModels are loaded when needed by default, but you can set it to load a specific ViewModel at launch, which can be useful in some scenarios.



来源:https://stackoverflow.com/questions/18976280/windows-phone-8-mvvm-viewmodels-and-app-xaml-cs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!