使Unity解析XAML中的视图 [英] Getting Unity to Resolve views in XAML

查看:91
本文介绍了使Unity解析XAML中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从MVVM开始,并且开始了解事物.我目前正在试验Cinch框架,尽管到目前为止我还没有致力于它.
我通过在视图的代码背后引用ViewModel并将其带有[Dependency]的属性引用到ViewModels中,从而将ViewModels注入到Views中,在setter中,它使用Unity将DataContext设置为正确的视图.我想这很巧妙.

I'm starting out with MVVM, and I'm starting to understand things. I'm currently experimenting with the Cinch framework, though I'm not committed to it as of yet.
I was injecting the ViewModels into the Views using by having a reference to the ViewModel in the codebehind of the view, with the property having a [Dependency] on it, and in the setter it sets the DataContext to the right view, using Unity. Neat trick, I thought.

我正在尝试让我的应用程序作为单个窗口工作,并带有注入的视图(与多个窗口相反,要处理它们的打开/关闭) 我将视图从Windows更改为UserControls,并在主窗口中添加了一个. 那行得通,但是从来没有注入过ViewModel,大概是因为XAML不使用Container.Resolve创建视图,就像我创建视图并将其手动添加到使用Resolve的代码中时一样,[Dependency]已创建

I'm trying to get my app to work as a single Window, with injected views (As opposed to multiple windows and dealing with opening\closing them) I changed my views from Windows to UserControls, and added a to the main window. That worked, but the ViewModel was never injected, presumably because the XAML doesn't use Container.Resolve to create the view, as when I created the view and added it manually in the code-behind using Resolve, the [Dependency] was created.

如何设置窗口,以便如果通过XAML添加视图,或者由于UI操作等导致视图发生更改,那么它会通过Unity获取它,从而使其发挥神奇的作用? /p>

How can I set up my window, so that if I add a view through XAML, or the view gets changed as a result of a UI action etc, it gets it through Unity, so that it can work its magic?

推荐答案

解决问题的方法是使您的窗口也具有ViewModel,其中UserControls的ViewModels作为其属性公开.然后在窗口的XAML中,只需使用Binding机制将UserControl的DataContext绑定到主ViewModel的适当属性.而且由于该主要ViewModel是从Unity容器解析的,因此可以根据需要注入所有其他ViewModel.

The way to solve your problem is to make your window to have a ViewModel as well, with ViewModels of UserControls exposes as properties on it. Then in your XAML for a window you'd simply use Binding mechanism to bind UserControl's DataContexts to proper properties of your your main ViewModel. And since that main ViewModel is resolved from Unity container it would have all other ViewModel-s injected as needed.

这篇关于使Unity解析XAML中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆