1. 程式人生 > 其它 >WPF Toolkit.Mvvm框架與IOC注入學習

WPF Toolkit.Mvvm框架與IOC注入學習

準備

專案建立引用

 

 

 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部落格