Toolkit.Mvvm Ioc

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Toolkit.Mvvm.DependencyInjection;
using System;

internal class ViewModelLocator
{
    public ViewModelLocator()
    {
        ConfigureServices();
    }

    /// <summary>
    /// Configures the services for the application.
    /// </summary>
    private IServiceProvider ConfigureServices()
    {
        var services = new ServiceCollection();

        // Services
        // services.AddSingleton<IContactsService, ContactsService>();
        // services.AddSingleton<IPhoneService, PhoneService>();

        // Viewmodels
        services.AddTransient<MainViewModel>();

        var serviceProvider = services.BuildServiceProvider();
        Ioc.Default.ConfigureServices(serviceProvider);

        return serviceProvider;
    }
    
    public MainViewModel? MainVM { get { return Ioc.Default.GetService<MainViewModel>(); } }

}

  

App.xaml
<Application.Resources>
     <local:ViewModelLocator x:Key="Locator"/>
</Application.Resources>

view.xaml
<Window x:Class="MainWindow"  
                         DataContext="{Binding Source={StaticReource Locator},Path =MainVM}"
</Window>

  

posted @ 2022-10-30 20:37  dongzhaosheng73  阅读(37)  评论(0编辑  收藏  举报