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

相关推荐
咩图2 天前
WPF+Prism8.0.0.1909+C#创建一个桌面程序
c#·wpf·prism
雁于飞2 天前
分布式基础
java·spring boot·分布式·spring·wpf·cloud native
oioihoii2 天前
WPF入门指南:解析默认项目结构
wpf
极客智造2 天前
深入解析 ReactiveUI:WPF 响应式 MVVM 开发的 “终极方案”
wpf
Macbethad4 天前
使用WPF编写一个多维度伺服系统的程序
大数据·hadoop·wpf
lingxiao168884 天前
WPF Prism框架应用
c#·wpf·prism
Macbethad4 天前
使用WPF编写一个Ethercat主站的程序
wpf
难搞靓仔4 天前
WPF 弹出窗体Popup
wpf·popup
Macbethad4 天前
使用WPF编写一个MODBUSTCP通信的程序
wpf
unicrom_深圳市由你创科技4 天前
Avalonia.WPF 跨平台图表的使用
wpf