dotNET
dotNET

Reputation: 35400

Why ViewModelLocator members are not static

Why the constructor and members of ViewModelLocator in MVVM Light are not static? Considering that I perform IOC registration process in the constructor like this:

SimpleIoc.Default.Register<MainWindowVM>();

does this mean every time I use it in a view (XAML), it will create a new instance of ViewModelLocator and thus register my classes over and over?

Plus what if I need to access it in the code? Do I need to create an instance of ViewModelLocator in every place?

Upvotes: 1

Views: 768

Answers (1)

Franz Wimmer
Franz Wimmer

Reputation: 1487

The ViewModelLocator from MVVMLight isn't designed static nor is it Singleton. This is because you register a global instance in your 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>

At this point, the constructor of the ViewModelLocator class gets called and you can use the instance in your views:

<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>

Upvotes: 3

Related Questions