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

标签 c# mvvm windows-phone-8 viewmodel

我一直在研究 MVVM 模式并在 Windows Phone 8 应用程序中将其付诸实践,我对在应用程序中初始化和访问 ViewModels 的最佳实践有疑问。

当我从 WP8 SDK 模板创建一个数据绑定(bind)应用程序时,我注意到 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?

最佳答案

有许多不同的方法来实例化 ViewModel。其中一些将在启动时实例化所有 View 模型,而另一些则在需要时才会实例化 ViewModel。

在下面的博文中,您将找到一些实例化 ViewModel 的可能方法:

MVVM Instantiation Approaches

回答您的问题; 1.- 按照您的方法,您必须在 App.xaml.cs 文件中为所有 ViewModel 定义成员。 2.- 您可以采用在需要时才实例化 ViewModel 的方法。

存在一些工具包,例如 MVVM LightCaliburn Micro ,这简化了 MVVM 模式的实现。我个人使用MVVM Light Toolkit ,它使用定位器方法。使用此工具包,默认情况下会在需要时加载 ViewModel,但您可以将其设置为在启动时加载特定的 ViewModel,这在某些情况下很有用。

关于c# - Windows Phone 8 - MVVM ViewModels 和 App.xaml.cs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18976280/

相关文章:

c# - 在 C# 中获取 iCloud 联系人列表

wpf - Windows 10 UWP - Windows Phone 模拟器上的空白

c# - 在 Windows Phone 8 应用程序中打开 WebP 图片格式

c# - 从本地存储读取数据时出现 NullReferenceException

c# - 在 C# 中查看返回值

c# - 读取 XML 或 JSON 文件而不是 SQL Server

c# - 使用自连接在 LINQ 中查询

c# - 如何使用mvvm模式更改标签内容

wpf - WPF MVVM 应用程序的最佳设计模式

ExtJS 5.1 : Binding record value to component property