欢迎来到陆季疵的博客

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

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

 


作者:@涛哥
本文为作者原创,转载请注明出处:https://www.cnblogs.com/taogeli/p/16046892.html


准备

社区工具包案例  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 @   陆季疵  阅读(5455)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
//《!--看板娘--> //https://www.cnblogs.com/ZTianming/p/14618913.html
点击右上角即可分享
微信分享提示