2017-02-13 36 views
0

我試圖做一個WPF應用程序豈不working.Also我在我的代碼的屬性注入該也給出了一個空引用。 這是因爲沒有重寫複合容器,如果是這樣的話/在哪裏給一個沒有棱鏡的應用程序的複合容器。 我的代碼是這樣的 在XAML文件的設計實例設置爲視圖模型和CS文件就像MEF進口和出口,而無需使用prism.When我試圖impoting構造通過MEF讓我的視圖模型視圖不工作

MainWindow.xaml.cs

public MainWindow() 
    { 
     InitializeComponent();    
    } 

    [ImportingConstructor] 
    public MainWindow(MainWindowViewModel viewModel) :this() 
    { 
     this.DataContext = viewModel; 
     this.ViewModel = viewModel; 
    } 
    public MainWindowViewModel ViewModel { get; set; } 

[Export] 
public class MainWindowViewModel 
{  
} 

在MainWindow.xaml.cs的構造函數的斷點不打在所有。內部視圖模型屬性注入也沒有打。 我該如何解決這個問題?

回答

0

這裏使用PRISM 5的例子,但它會工作以同樣的方式PRISM 6.2.0。

你需要從App.xaml中刪除啓動URI。 然後確保安裝了PRISM.MEF NuGet軟件包。 編寫一個如下所示的引導程序。 (請注意,引導程序基類有一系列的方法對所有這種設置一個適當的位置來覆蓋。我在爲簡單起見一個方法堅持了一切。)

public class MyBootstrapper : MefBootstrapper 
{ 
    protected override DependencyObject CreateShell() 
    {    
     var catalog = new AggregateCatalog(); 
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(MyBootstrapper).Assembly)); 
     var container = new CompositionContainer(catalog); 
     var shell = container.GetExport<MainWindow>().Value; 
     shell.Show(); 
     return shell; 
    } 
} 

添加Export屬性的主窗口。這將需要爲這條線在引導程序:

var shell = container.GetExport<MainWindow>().Value; 

[Export] 
public partial class MainWindow : Window{} 

現在所有剩下的是運行引導程序:

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) 
    { 
     var bootstrapper = new MyBootstrapper(); 
     bootstrapper.Run(); 
    } 
} 

更新

你可以得到一個不錯的手柄通過此處所述的示例進行MEF:

https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx

更新

下面是實現引導程序的更清潔的方式。

public class MyBootstrapper : MefBootstrapper 
    { 
     protected override AggregateCatalog CreateAggregateCatalog() 
     { 
      return new AggregateCatalog(); 
     } 

     protected override void ConfigureAggregateCatalog() 
     { 
      AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(MyBootstrapper).Assembly)); 
     }  

     protected override CompositionContainer CreateContainer() 
     { 
      return new CompositionContainer(AggregateCatalog); 
     } 

     protected override void ConfigureContainer() 
     { 
      base.ConfigureContainer(); 
     } 

     protected override DependencyObject CreateShell() 
     { 
      var shell = Container.GetExport<MainWindow>().Value; 
      shell.Show(); 
      return shell; 
     } 
    }