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

相关推荐
清风徐来Groot2 小时前
WPF之Style
wpf
rollingman9 小时前
WPF GroupBox 淡入淡出
wpf
yy76349666813 小时前
WPF 之 简单高效的Revit多语言支持方案
java·大数据·linux·服务器·wpf
张人玉1 天前
WPF 触发器详解:定义、种类与示例
c#·wpf·1024程序员节·布局控件
rollingman1 天前
WPF ComboBox 样式
wpf·combobox·textbox
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(三)
wpf·界面控件·devexpress·ui开发·1024程序员节
张人玉1 天前
WPF 核心概念笔记(补充示例)
c#·wpf·1024程序员节·布局控件
亦陈不染2 天前
WPF-MVVM的简单入门(第一个MVVM程序)
wpf
FuckPatience2 天前
WPF TreeView 条目右键命令 ContextMenu按钮绑定命令
wpf
The 旺2 天前
【案例实战】HarmonyOS分布式购物车:多设备无缝协同的电商体验
分布式·wpf·harmonyos