Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding WPF OnStartUp results in multiple window instances

Tags:

mvvm

wpf

In a simple MVVM approach I link the MainWindow to a ViewModel by overriding OnStartup in App.xaml.

  public partial class App : Application
  {

    protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);

      MainWindow window = new MainWindow();
      var viewModel = new MainWindowViewModel();
      window.DataContext = viewModel;
      window.Show();
    }

  }

This results in two instances of the MainWindow when I run the WPF application. Shouldn't it only result in one as I am overriding the startup?

One of the window is showing the correct DataContext (ViewModel), while the other is not.

like image 985
Kman Avatar asked May 23 '12 12:05

Kman


1 Answers

In App.xaml:

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">

Remove The StartupUri. That will stop that second window loading.

like image 155
Alex Curtis Avatar answered Oct 20 '22 18:10

Alex Curtis