Question

I have a View:

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

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

    public IStartWindowViewModel ViewModel { get; private set; }
}

And an appropriate ViewModel:

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

UPD(based on @Blachshma answer): I can`t inject StartWindow view into my App using code:

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

because parameterless constructor need by 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();
        }
    }

Now, I want to instantiate in app.cs my view via constructor injection. What should I do for it?

Also, Im looking for best practices forMEF/MVVM` solutions (some sample code for this would be a great idea).

p.s. .NET 4.5

Était-ce utile?

La solution

If you want to get an instance of the view using MEF, you first of all need to Export the view. So add the [Export] attribute to your StartWindow class:

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

Now, in your App class use ImportingConstrutor to get the instance:

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

Regarding good articles on MVVM, I recommend Josh Smith's blog

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top