wpf view的viewmodel依赖注入
时间: 2023-07-03 10:13:01 浏览: 52
在 WPF 中,通常使用 MVVM 架构模式,其中视图(View)和视图模型(ViewModel)是分离的。为了实现依赖注入(Dependency Injection),可以使用某些第三方框架,例如 Prism、Autofac 等。
以 Prism 为例,可以在 App.xaml.cs 中初始化容器并注册服务:
```
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IMyService, MyService>();
}
```
然后,在 View 中使用 Prism 提供的 ViewModelLocator,将视图模型与容器中的服务进行绑定:
```
<UserControl x:Class="MyApp.Views.MyView"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
```
最后,在 ViewModel 中通过构造函数注入服务:
```
public class MyViewModel
{
private readonly IMyService _myService;
public MyViewModel(IMyService myService)
{
_myService = myService;
}
}
```
这样,就实现了在 WPF 中使用依赖注入来管理视图模型中的依赖项。