Overriding WPF OnStartUp results in multiple instances of the window

In a simple MVVM approach, I associate MainWindow with a ViewModel, 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 MainWindow when the WPF application starts. Won't this lead to one, as I redefine the launch?

One of the windows displays the correct DataContext (ViewModel), and the other does not.

+6
source share
1 answer

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 StartupUri. This will stop loading the second window.

+10
source

Source: https://habr.com/ru/post/916448/


All Articles