WPF UserControl 上的依赖注入(Windsor)
在 MainView 中使用 DI 没有问题: 我将窗户添加到容器中,启动时我显示已从容器中拉出的窗户。但是,如果我将一个用户控件作为 xaml 标记添加到我的主视图中,wpf 视图引擎它将自动为其创建新实例,而无需取出我添加到容器中的 UserControl。如何强制 WPF 视图引擎搜索组件view/xamal 需要将其放入我的容器中而不是创建新容器?
Using DI into MainView is not problem:
I added my windows into my container and on start up I show my windows that has been pulled out from my container. But If I have a usercontrol added into my main view as xaml tag, wpf view engine it will create automatically new instance for it without pulling out the UserControl I added into my container as well.. How can I force WPF view engine to search component required by view/xamal into my container instead of creating new one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果不修改 XAML,就无法做到这一点。您可以考虑一些解决方法,例如创建一个从
ContentControl
继承的控件,该控件会将依赖项注入到其Content
中,但我不会推荐这种方法,除非您别无选择。我建议使用最好的 WPF 模式 - MVVM。这个想法是拥有一个 ViewModel 的层次结构,所有这些都将使用 IoC 容器和适当的构造函数注入来创建。此外,您还将拥有视图层次结构,每个视图仅依赖于相应的 viewModel,该视图模型将被传递到视图的 DataContext 中。这种方法将允许您在 WPF 应用程序中很好地使用 DI。
There is no way to do it without modifying your XAML. You can think about some workarounds, for example create a control inherited from
ContentControl
which will inject dependencies into itsContent
but I would not recommend this approach, only if you have no choice.What I would recommend is to use the best WPF pattern - MVVM. The idea is to have a hierarchy of ViewModels, all of them will be created using IoC container with proper constructor injection. Also you will have hierarchy of views, each view will depend only on corresponding viewModel which will be passed into view's
DataContext
. This approach will allow you to use DI in WPF application nicely.我想我明白你建议我
在启动时从容器中拉出 MainWindow
并且 Mainwindow 看起来像
I think I understood what you suggested me
where MainWindow is pulled out from container at startup
and Mainwindow looks like