且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Unity从usercontrol viewmodel到customUsercontrol Viewmodel的依赖注入

更新时间:2023-10-08 20:07:28

解决方案很简单.不要使用 DI/IoC 容器来注入控件.它不会起作用,也不应该起作用.

Solution is simple. Don't use DI/IoC container to inject controls. It's not going to work and was never supposed to work.

用户控件(与视图相反)是自包含的,可以与其他应用程序或不需要容器的 IDE 设计人员一起开箱即用.否则,它们将无法与设计器很好地合作,因为 Xaml 设计器没有 DI/IoC 的概念,并且不知道如何解析/实例化某个类并且需要无参数构造函数.此外,用户控件"不会将其逻辑拆分为 ViewModel.

User controls (in contrast to views) are meant to be self-contained and work out of the box with other applications or the IDE designer w/o requiring a container. Otherwise they just won't work well with the designer, as the Xaml designer has no concept of DI/IoC and won't know how to resolve/instantiate a certain class and requires an parameterless constructor. Also a "user control" doesn't split it's logic into a ViewModel.

另一面的视图只是一个没有代码的 UI 模板.它也派生自 WindowsUserControl 类,但没有自己的逻辑并且不可重用.视图总是非常特定于特殊的 ViewModel,而 ViewModel 非常特定于一个应用程序.对于视图,可以使用 DI,但只能注入 ViewModel(即取决于您是采用 View-first 还是 ViewModel-first 方法).

A view on other side is just an UI template without code. It also derives from Windows or UserControl class, but has no logic of it's own and is not reusable. A view is always very specific for a special ViewModel and ViewModels are very specific to one application. For views one can use DI, but only to inject the ViewModel (i.e. depending if you are going for View-first or ViewModel-first approach).

附带说明,您的 UserControl1ViewModel 违反了 MVVM,因为您的 VM 引用了您的视图,这违背了 MVVM 的全部目的

On a side note, your UserControl1ViewModel violates MVVM as your VM has references to your View, which beats the whole purpose of MVVM