Overriding WPF OnStartUp results in multiple window instances

mvvm, wpf

Solution

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.

Problem

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.

Original source