sonnemaf / ToolkitMvvmDemo

Demo project using the Toolkit.Mvvm package.
13 stars 1 forks source link

try to use ViewModelLocator with ToolkitMvvm #2

Closed hippieZhou closed 4 years ago

hippieZhou commented 4 years ago

I like this toolkit so much and will change mvvmlight to Microsoft.Toolkit.Mvvm,I have learned a lot about the features of this package from your sample code. By the way, I like use ViewModelLocator in MVVM Pattern,and define static object for the current instance in ViewModel is not a good way in some way, so here are my sample code:

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        Ioc.Default.ConfigureServices(services =>
        {
            services.AddSingleton<ILogger, DebugLogger>();
            services.AddSingleton<MainViewModel>();
        });
    }

    public static MainViewModel Main => Ioc.Default.GetService<MainViewModel>();
}
<Application
    x:Class="MvvmDemoWPF.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MvvmDemoWPF"
    StartupUri="Views/Windows/MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <local:ViewModelLocator x:Key="Locator" />
        </ResourceDictionary>
    </Application.Resources>
</Application>
<Window
    x:Class="MvvmDemoWPF.Views.Windows.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:MvvmDemoWPF"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vm="clr-namespace:MvvmDemo.ViewModels;assembly=MvvmDemoLibrary"
    Title="MainWindow"
    Width="800"
    Height="450"
    DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
    FontSize="20"
    mc:Ignorable="d">
</Window>
sonnemaf commented 4 years ago

Your solution is totally OK. It is I think a personal preference. Use whatever you like best.