【问题标题】:Why ViewModelLocator members are not static为什么 ViewModelLocator 成员不是静态的
【发布时间】:2016-12-16 18:06:58
【问题描述】:

为什么 MVVM Light 中ViewModelLocator 的构造函数和成员不是静态的?考虑到我在构造函数中执行 IOC 注册过程是这样的:

SimpleIoc.Default.Register<MainWindowVM>();

这是否意味着每次我在视图 (XAML) 中使用它时,它都会创建一个 ViewModelLocator 的新实例,从而一遍又一遍地注册我的类?

另外,如果我需要在代码中访问它怎么办?我需要在每个地方都创建一个 ViewModelLocator 的实例吗?

【问题讨论】:

  • 不是单例吗?
  • @MikeEason:不,从 5.3 开始。
  • 因为这就是他们实现它的方式。人们远离静态的原因有很多。解耦以简化测试任务是一项主要任务。如果你真的想知道,你需要询问MVVM Light的开发者。

标签: c# wpf mvvm inversion-of-control mvvm-light


【解决方案1】:

来自 MVVMLight 的 ViewModelLocator 不是静态设计的,也不是单例的。这是因为您在 App.xaml 中注册了一个全局实例:

<Application x:Class="Project.App" 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             StartupUri="MainWindow.xaml" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             d1p1:Ignorable="d" 
             xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vm="clr-namespace:Acoustix.ViewModel">
    <Application.Resources>
        <ResourceDictionary>
            <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True"  />
        </ResourceDictionary>
    </Application.Resources>
</Application>

此时,ViewModelLocator 类的构造函数被调用,您可以在视图中使用该实例:

<Window x:Class="Project.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:system="clr-namespace:System;assembly=mscorlib"
        DataContext="{Binding Main, Source={StaticResource Locator}}" Icon="Assets/app.ico">
    <!-- ... -->
</Window>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2012-01-21
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2013-10-19
    相关资源
    最近更新 更多