2011-03-29 106 views
5

在MainView中使用DI并不成问题: 我将窗口添加到我的容器中并启动时显示已从我的容器中拉出的窗口。但是,如果我有一个用户控件添加到我的主视图作为XAML标记,WPF视图引擎它会自动创建新的实例,而无需拉出我添加到我的容器中的UserControl以及..如何强制WPF视图引擎搜索组件视图/ xamal需要我的容器,而不是创建一个新的?WPF UserControl上的依赖注入(Windsor)

+1

重复:HTTP:/ /stackoverflow.com/questions/2408873/how-do-i-inject-dependencies-to-user-controls-in-wpf – 2011-03-29 21:10:44

回答

2

如果不修改您的XAML,则无法执行此操作。您可以考虑一些解决方法,例如创建一个从ContentControl继承的控件,该控件会将依赖关系注入到Content中,但是如果没有其他选择,我不会推荐这种方法。

我会推荐的是使用最好的WPF模式 - MVVM。这个想法是有一个ViewModel的层次结构,所有这些都将使用IoC容器与适当的构造函数注入来创建。此外,您将拥有视图层次结构,每个视图仅取决于相应的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> 

,其中主窗口是由容器启动时

protected override void OnStartup(StartupEventArgs e) 
{ 
    GuyWire.Wire(); 
    ((Window)GuyWire.GetRoot()).Show();//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; } 
} 
+0

是的,就是这样。 – Snowbear 2011-03-29 21:50:51