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

相关推荐
FuckPatience2 天前
WPF 具有跨线程功能的UI元素
wpf
诗仙&李白2 天前
HEFrame.WpfUI :一个现代化的 开源 WPF UI库
ui·开源·wpf
He BianGu2 天前
【笔记】在WPF中Binding里的详细功能介绍
笔记·wpf
He BianGu2 天前
【笔记】在WPF中 BulletDecorator 的功能、使用方式并对比 HeaderedContentControl 与常见 Panel 布局的区别
笔记·wpf
123梦野3 天前
WPF——效果和可视化对象
wpf
He BianGu3 天前
【笔记】在WPF中Decorator是什么以及何时优先考虑 Decorator 派生类
笔记·wpf
时光追逐者3 天前
一款专门为 WPF 打造的开源 Office 风格用户界面控件库
ui·开源·c#·.net·wpf
He BianGu3 天前
【笔记】介绍 WPF XAML 中 Binding 的 StringFormat详细功能
笔记·wpf
Rotion_深4 天前
C# WPF使用线程池运行Action方法
c#·wpf·线程池
攻城狮CSU5 天前
WPF 深入系列.2.布局系统.尺寸属性
wpf