为什么MVVM Light中的ViewModelLocator的构造函数和成员不是静态的?考虑到我在构造函数中执行IOC注册过程,如下所示:
SimpleIoc.Default.Register<MainWindowVM>();这是否意味着每次我在视图(XAML)中使用它时,它都会创建一个新的ViewModelLocator实例,从而反复注册我的类?
另外,如果我需要在代码中访问它,该怎么办?我需要在每个地方创建一个ViewModelLocator实例吗?
发布于 2016-08-27 02:16:58
来自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>https://stackoverflow.com/questions/38872002
复制相似问题