簡體   English   中英

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

[英]Windows Phone 8 - MVVM ViewModels and App.xaml.cs

我一直在研究MVVM模式並將其應用到Windows Phone 8應用程序中,我對在應用程序中初始化和訪問ViewModel的最佳實踐有疑問。

當我從WP8 SDKs模板創建數據綁定應用程序時 ,我注意到App.xaml.cs文件中的這段代碼:

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();
    }
}

據我所知,這意味着App類包含MainViewModel作為靜態成員,並且在激活應用程序時,將加載ViewModel。

既然如此,我有以下問題:

  1. 如果我的應用程序有多個ViewModel,它們是否都會作為成員存儲在App.xaml.cs文件中?

  2. 如果同時加載每個ViewModel的數據,我該如何管理我的應用程序的內存? 是否可以卸載每個ViewModel的數據並僅加載我的View正在使用的ViewModel?

有許多不同的方法來實例化ViewModels。 其中一些將在啟動時實例化所有,而其他人在需要之前不會實例化ViewModel。

在以下博客文章中,您將找到一些實例化ViewModel的可能方法:

MVVM實例化方法

回答你的問題; 1.-按照您的方法,您必須在App.xaml.cs文件中為所有ViewModel定義成員。 2.-您可以遵循不需要實例化ViewModel的方法。

存在一些工具包,例如MVVM LightCaliburn Micro ,它們可以簡化MVVM模式的實現。 我個人使用MVVM Light Toolkit ,它使用Locator方法。 使用此工具包時,默認情況下會在需要時加載ViewModel,但您可以將其設置為在啟動時加載特定的ViewModel,這在某些情況下很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM