WPF UserControl 上的依赖注入(Windsor)

5

将DI引入MainView并不是问题: 我将我的窗口添加到容器中,并在启动时展示从容器中拉出的窗口。但是,如果我在主视图中添加了一个作为xaml标记的用户控件,WPF视图引擎会自动创建一个新实例,而不会将我添加到容器中的用户控件拉出。我该如何强制WPF视图引擎搜索视图/xamal所需的组件,并将其放入我的容器中,而不是创建新的实例?


1
如何在WPF中向用户控件注入依赖项? - Mark Seemann
2个回答

3

没有一种方法可以在不修改XAML的情况下完成此操作。您可以考虑一些解决方法,例如创建一个从ContentControl继承的控件,该控件将依赖项注入其Content中,但我不建议采用这种方法,除非您别无选择。

我建议使用最佳的WPF模式 - MVVM。其思想是拥有一组ViewModel的层次结构,所有这些ViewModel都将使用IoC容器创建,并进行适当的构造函数注入。此外,您还将拥有视图的层次结构,每个视图仅依赖于相应的viewModel,该viewModel将传递到视图的DataContext中。这种方法将使您能够很好地在WPF应用程序中使用DI。


2

我想我理解了你建议我的内容

<Window x:Class="DDDSample02.Wpf.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:presentation="clr-namespace:DDDSample02.Wpf.Views"
        Title="MainWindow" Height="384" Width="821">
    <Grid>
        <presentation:ProductsView DataContext="{Binding Path=ProductsPresenter}" />
    </Grid>
</Window>

在启动时,MainWindow从容器中拉出。

protected override void OnStartup(StartupEventArgs e)
{
    GuyWire.Wire();
    ((Window)GuyWire.GetRoot()).Show();//MainWindow
}

而MainWindow看起来像

public partial class MainWindow : Window
{

    public MainWindow(DDDSample02.ViewModel.MainWindowPresenter presenter)
    {
        InitializeComponent();
        this.DataContext = presenter;
    }

}

public class MainWindowPresenter
{
    public MainWindowPresenter(ProductsPresenter productPresenter)
    {
        this.ProductsPresenter = productPresenter;
    }

    public ProductsPresenter ProductsPresenter { get; private set; }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接