wpf依赖注入驱动的 MVVM实现(含免费源代码demo)

bg:学avalonia,发现通过di也可以实现绑定,可以代替Prism框架的一个功能(Prism看到wpf的挺久没更新了)。

1、首先Nuget中安装tookit和di

2、View和ViewModel正常写

3、创建ServiceLocator,构造函数注册viewModel后就可以从容器中获取

cs 复制代码
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace wpf_test
{
    public class ServiceLocator
    {
        private readonly IServiceProvider _serviceProvider;

        // 从容器中获取 MainWindowViewModel 实例
        public MainWindowViewModel MainWindowViewModel =>
            _serviceProvider.GetService<MainWindowViewModel>();


        public ServiceLocator()
        {
            
            var serviceCollection = new ServiceCollection();

            // 注册ViewModel
            serviceCollection.AddSingleton<MainWindowViewModel>();

            // 构造容器
            _serviceProvider = serviceCollection.BuildServiceProvider();
        }
    }
}

4、ViewModel 绑定到 View 的 DataContext 上

cs 复制代码
DataContext="{Binding MainWindowViewModel, Source={StaticResource ServiceLocator}}"

样例在项目wpf_test中:https://github.com/zzp229/Mvvmdb

相关推荐
Chris _data9 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
布吉岛的石头10 天前
Java 程序员第 43 阶段05:微服务整合大模型,跨服务调用架构设计实战,Seata分布式事务实战
wpf
步步为营DotNet10 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
芒鸽10 天前
HarmonyOS 分布式开发实战:设备协同、数据共享与跨设备迁移
分布式·wpf·harmonyos
Volunteer Technology10 天前
Flink状态管理与容错(二)
大数据·flink·wpf
happyprince11 天前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
bugcome_com11 天前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf
小满Autumn12 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
政沅同学12 天前
基于 C# WPF + HALCON 的工业视觉算法工具框架(开源)
开发语言·c#·wpf
happyprince12 天前
03_verl-设计理念与核心原理
wpf