启动组合问题

时间:2013-01-31 21:10:17

标签: c# wpf mvvm mef constructor-injection

我有View

internal partial class StartWindow : Window
{
    public StartWindow()
    {
        InitializeComponent();
    }

    [ImportingConstructor]
    public StartWindow(IStartWindowViewModel viewModel)
        :this()
    {
        ViewModel = viewModel;
    }

    public IStartWindowViewModel ViewModel { get; private set; }
}

适当的ViewModel

    [Export]
    internal class StartWindowViewModel : IStartWindowViewModel
    {
        public IEnumerable<Customer> Customers { get; set; }
    }

UPD (基于@Blachshma答案): 我无法使用代码将StartWindow视图注入我的应用程序:

public class App
{
     [ImportingConstructor]
     public App(StartWindow window)
     {
          // Do whatever you need
     }

因为App.g.cs需要无参数构造函数:

internal partial class App : System.Windows.Application {

        /// <summary>
        /// Application Entry Point.
        /// </summary>
        [System.STAThreadAttribute()]
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        public static void Main() {
            TransparentNotification.App app = new TransparentNotification.App();
            app.Run();
        }
    }

现在,我希望通过app.csview我的constructor injection中实例化。我该怎么做呢?

此外,我m looking for best practices for MEF / MVVM`解决方案(一些示例代码对此非常有用)。

P.S。 .NET 4.5

1 个答案:

答案 0 :(得分:0)

如果要使用MEF获取视图实例,首先需要导出视图。 因此,将[Export]属性添加到StartWindow类:

[Export]
partial class StartWindow : Window
{
  ...

现在,在您的App课程中使用ImportingConstrutor来获取实例:

public class App
{
     [ImportingConstructor]
     public App(StartWindow window)
     {
          // Do whatever you need
     }

关于MVVM上的好文章,我建议Josh Smith's blog