欢迎来到陆季疵的博客

人生莫作远行客,远行莫戍黄沙碛。黄沙碛下八月时, 霜风裂肤百草衰。尘沙晴天迷道路,河水悠悠向东去。 胡笳听彻双泪流,羁魂惨惨生边愁。原头猎火夜相向, 马蹄蹴蹋层冰上。不似京华侠少年,清歌妙舞落花前。

WPF Toolkit.Mvvm框架与IOC注入学习

准备

社区工具包案例  GitHub - CommunityToolkit/WindowsCommunityToolkit: The Windows Community Toolkit is a collection of helpers, extensions, and custom controls. It simplifies and demonstrates common developer tasks building UWP and .NET apps for Windows 10. The toolkit is part of the .NET Foundation.

项目创建引用

 

 

 App.xaml中删除启动配置

 

 

 cs文件中的代码

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static IHost? Host { get; private set; }
        public App()
        {
            //Ioc.Default.ConfigureServices(new ServiceCollection().AddSingleton<IFoo, Foo>().BuildServiceProvider());
            // Text1 =Ioc.Default.GetService<IFoo>().GetText();
            Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    ConfigureServices(services);
                   
                })
                .ConfigureLogging((context, logging) =>
                {
                    logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                    logging.AddDebug();
                    //logging.AddNLog();
                })
                .Build();

        }
        private void ConfigureServices(IServiceCollection services)
        {
            
            // Add Services
            services.AddSingleton<IDataService, DataService>();
            
            services.AddSingleton<MainWindow>();
            services.AddSingleton<IDataService, DataService>();
            services.AddSingleton<MainWindowViewModel>();
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            await Host!.StartAsync();
            //此处也可以在xaml中配置
            var window = Host.Services.GetRequiredService<MainWindow>();
            window.DataContext=Host.Services.GetRequiredService<MainWindowViewModel>();
            window.Show();
            base.OnStartup(e);
        }
        protected override async void OnExit(ExitEventArgs e)
        {
            await Host!.StopAsync();
            base.OnExit(e);
        }

    }

窗体前台代码

<Window x:Class="WpfApp1.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel x:Name="sp1">
            <Button Margin="10" Command="{Binding ExecCommand}" Content="Button" />
            <TextBlock Margin="10" Text="{Binding Status}" />
            <ProgressBar Margin="10" Value="{Binding ProgressValue}" Minimum="0" Maximum="100" />
        </StackPanel>
    </Grid>
</Window>

模型

    public class DataService : IDataService
    {
        public IEnumerable<PersonModel> GetAll()
        {
            IEnumerable<PersonModel> result = new List<PersonModel>()
            {
                new PersonModel() { Name = "John Doe", Id = 1 },
                new PersonModel() { Name = "Jane Doe", Id = 2 }
            };

            return result;
        }
    }
    public interface IDataService
    {
        IEnumerable<PersonModel> GetAll();
    }
    public class PersonModel
    {
        public int Id { get; set; }
        public string Name { get; set; } = String.Empty;
    }

视图模型

using DependencyInjection.WPF.Models;
using DependencyInjection.WPF.Services;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfApp1.ViewModels
{
    public class MainWindowViewModel : ObservableObject
    {
        private IDataService _dataService;
        public ObservableCollection<PersonModel> People => _people;
        private readonly ObservableCollection<PersonModel> _people = new ObservableCollection<PersonModel>();
        public MainWindowViewModel(IDataService dataService)
        {
            this._dataService = dataService;
            _status = "Hello";
            ExecCommand = new AsyncRelayCommand(ExecAsync);
            OnWindowLoaded();
        }

        private void OnWindowLoaded()
        {
            if (_dataService != null)
            {
                foreach (var person in _dataService.GetAll())
                {
                    People.Add(person);
                }
            }
        }

        private string _status;

        public string Status
        {
            get => _status;
            set => SetProperty(ref _status, value);
        }
        private int _progressValue;

        public int ProgressValue
        {
            get => _progressValue;
            set => SetProperty(ref _progressValue, value);
        }
        public ICommand ExecCommand { get; }
        private async Task ExecAsync()
        {
            Status = "Processing...";

            await Task.Run(async () =>
            {
                for (int i = 0; i <= 100; i++)
                {
                    ProgressValue = i;

                    await Task.Delay(100);
                }
            });
            Status = "Complete";
        }

    }

}

 

数据上下文的配置方法二

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>(); } }

}  

 

 

 

框架简介  Microsoft.Extensions 探索 / 依赖注入(DI) - 知乎 (zhihu.com)

关于消息的使用参考链接  Wpf在.Net 6 下该用哪个Mvvm框架-Microsoft.Toolkit.Mvvm_小兵小卒的博客-CSDN博客_wpf高性能mvvm框架

[WPF] 使用 MVVM Toolkit 构建 MVVM 程序 - dino.c - 博客园 (cnblogs.com)

官方文档 MVVM - 深入介绍 MVVM Light Messenger | Microsoft Docs

Microsoft.Toolkit.Mvvm 使用记录 | ConorLuo 博客 (buctllx.github.io)

MVVMtoolkit 学习_isDataWork的博客-CSDN博客

 

posted @ 2022-03-23 21:19  陆季疵  阅读(5261)  评论(1编辑  收藏  举报
//《!--看板娘--> //https://www.cnblogs.com/ZTianming/p/14618913.html