我在MS VS 2015 Professional(.NET Framework 4.6)中开发WPF MVVM应用程序.当我运行我的WPF MVVM应用程序时,我的应用程序主窗口的两个实例正在显示.它为什么有位置?下面是我的应用程序主窗口的标记 - MainWindow.xaml:
下面是MainWindow.xaml.cs的代码:
using System.Windows; namespace SuperMrgaChartDrawer { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }
以下是App.xaml.cs的代码:
using System; using System.Windows; using SuperMrgaChartDrawer.ViewModel; namespace SuperMrgaChartDrawer { public partial class App : Application { ////// My application OnStartup handler. /// /// 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(); } } }
这个错误的原因是什么?我该怎么做才能消除这个错误.请帮忙.我们将非常感谢您的帮助.
你的App.xaml
包含StartupUri="MainWindow.xaml"
.此属性由WPF应用程序模板添加.StartupUri
如果要手动显示窗口,请删除.
此外,这是添加事件处理程序的相当奇特的方式:
EventHandler handler = null; handler = delegate { viewModel.RequestClose -= handler; window.Close(); }; viewModel.RequestClose += handler;
因为RequestClose
就是EventHandler
,你可以从上面的代码替换(这是主窗口,因此,没有必要退订):
viewModel.RequestClose += (sender, args) => window.Close();