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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM