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

相关推荐
笺上知微1 小时前
基于HelixToolkit.SharpDX 渲染3D模型
wpf
晓纪同学1 天前
WPF-03 第一个WPF程序
大数据·hadoop·wpf
光电大美美-见合八方中国芯1 天前
用于无色波分复用光网络的 10.7 Gb/s 反射式电吸收调制器与半导体光放大器单片集成
网络·后端·ai·云计算·wpf·信息与通信·模块测试
晓纪同学1 天前
WPF-02体系结构
wpf
晓纪同学1 天前
WPF-01概述
wpf
海盗12342 天前
OxyPlot 在 WPF 中的使用
.net·wpf
晓纪同学2 天前
WPF-04 XAML概述
wpf
△曉風殘月〆2 天前
如何在WPF中捕获窗口外的事件
wpf
爱吃烤鸡翅的酸菜鱼4 天前
Java 事件发布-订阅机制全解析:从原生实现到主流中间件
java·中间件·wpf·事件·发布订阅
武藤一雄4 天前
WPF中ViewModel之间的5种通讯方式
开发语言·前端·microsoft·c#·wpf