当我运行WPF MVVM应用程序时,显示主窗口的两个实例

本文关键字:窗口 实例 两个 显示 WPF 运行 MVVM 应用程序 | 更新日期: 2023-09-27 18:26:56

我在MS VS 2015 Professional(.NET Framework 4.6)中开发WPF MVVM应用程序。当我运行WPF MV虚拟机应用程序时,会显示应用程序主窗口的两个实例。为什么它有位置?下面是我的应用程序主窗口的标记-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>

以下是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
    {
        /// <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();
        }
    }
}

这个错误的原因是什么?我该怎么做才能消除这个错误。请帮忙。我们将非常感谢您的帮助。

当我运行WPF MVVM应用程序时,显示主窗口的两个实例

您的App.xaml包含StartupUri="MainWindow.xaml"。此属性由WPF应用程序模板添加。如果要手动显示窗口,请删除StartupUri

此外,这是添加事件处理程序的一种非常奇特的方式:

EventHandler handler = null;
handler = delegate
{
    viewModel.RequestClose -= handler;
    window.Close();
};
viewModel.RequestClose += handler;

由于RequestCloseEventHandler,您可以替换上面的代码(这是主窗口,因此无需取消订阅):

viewModel.RequestClose += (sender, args) => window.Close();