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

I am studying the MVVM pattern and putting it into practice in a Windows Phone 8 application, and I have a question about the best methods for initializing and accessing ViewModels in an application.

When I create an application to bind data from the WP8 SDK 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, this means that the App class contains the MainViewModel as a static member, and when the application is activated, the ViewModel is loaded.

In this case, I have the following questions:

  • If there are several ViewModels in my application, will all of them be saved as members inside the App.xaml.cs file?

  • If each ViewModel file is loaded at the same time, how can I manage the application memory? Is it possible to unload every ViewModel information and load only the ViewModel that is used by my view?

+8
c # viewmodel mvvm windows-phone-8
source share
1 answer

There are many different approaches to creating instances of ViewModels. Some of them will start all instances at startup, while others will not create an instance of ViewModel until needed.

In the following blog, you will find several possible approaches to creating an instance of ViewModel:

MVVM Configuration Approaches

Answering your questions; 1. After your approach, you will need to define members for all your ViewModels in your App.xaml.cs. 2.- You can follow an approach that does not instantiate a ViewModel until it is needed.

There are some tools, such as MVVM Light or Caliburn Micro , that facilitate the implementation of the MVVM template. I personally use the MVVM Light Toolkit , which uses the Locator approach. Using this toolkit, ViewModels are loaded as needed by default, but you can set it to load a specific ViewModel at startup, which may be useful in some scenarios.

+9
source share

All Articles