I develop WPF MVVM application in MS VS 2015 Professional (.NET Framework 4.6). When I run my WPF MVVM application then two instances of my application main window are displaying. Why does it have place? Below is markup of my application main window - MainWindow.xaml:
<Window x:Class="SuperMrgaChartDrawer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SuperMrgaChartDrawer"
xmlns:vm="clr-namespace:SuperMrgaChartDrawer.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>
Below is code of MainWindow.xaml.cs:
using System.Windows;
namespace SuperMrgaChartDrawer
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
And below is code of App.xaml.cs:
using System;
using System.Windows;
using SuperMrgaChartDrawer.ViewModel;
namespace SuperMrgaChartDrawer
{
public partial class App : Application
{
/// <summary>
/// My application OnStartup handler.
/// </summary>
/// <param name="e"></param>
protected override void OnStartup(StartupEventArgs e)
{
// Call OnStartup in base class.
base.OnStartup(e);
// Create an instance of application main window.
MainWindow window = new MainWindow();
// Create an instance of View Model of main window.
var viewModel = new MainWindowViewModel();
// Define handler for "Main Window Request Close" event
// and subscribe on it.
EventHandler handler = null;
handler = delegate
{
viewModel.RequestClose -= handler;
window.Close();
};
viewModel.RequestClose += handler;
// Set MainWindowViewModel as main window data context.
window.DataContext = viewModel;
// Display main window.
window.Show();
}
}
}
What is the reason of this error? What should I do to eliminate this error. Please help. Your help will be highly appreciated.
Your App.xaml contains StartupUri="MainWindow.xaml".
This attribute is added by WPF application template. Remove StartupUri, if you want to show window manually.
Besides, this is rather exotic way to add event handler:
EventHandler handler = null;
handler = delegate
{
viewModel.RequestClose -= handler;
window.Close();
};
viewModel.RequestClose += handler;
Since RequestClose is EventHandler, you can replace code from above (this is main window, so, there's no need to unsubscribe):
viewModel.RequestClose += (sender, args) => window.Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With