MainWindow的构造函数获取调用两次 [英] MainWindow constructor getting called twice

查看:384
本文介绍了MainWindow的构造函数获取调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置的的DataContext 主窗口到视图模型在应用.OnStartup 。这样做时,我注意到,主窗口()构造函数获取调用两次,我看到2个窗口打开。你知道什么造成这种现象?我的代码如下:

 公共部分类应用:应用
{
保护覆盖无效OnStartup( StartupEventArgs E)
{
base.OnStartup(E);

主窗口的主窗口=新的主窗口();

//创建到主窗口绑定视图模型。
MainWindowViewModel mainWindowViewModel =新MainWindowViewModel();

//注册处理,使得当mainWindowViewModel要求被关闭时,关闭该窗口。
mainWindowViewModel.RequestClose + =委托(System.Object的0,System.EventArgs EventArgs的)
{
mainWindow.Close();
};


mainWindow.DataContext = mainWindowViewModel;

mainWindow.Show();
}
}


解决方案

有仍是 的StartupUri 萦绕在的App.xaml 我怀疑...


I am trying to set the DataContext of the MainWindow to its ViewModel in App.OnStartup. I noticed when doing that, MainWindow() constructor is getting called twice and I see 2 windows opened. Any idea whats causing this behavior ? My code is as follows:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        MainWindow mainWindow = new MainWindow();

        // Create the ViewModel to which the main window binds.
        MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();

        // Register handle such that when the mainWindowViewModel asks to be closed, close the window.
        mainWindowViewModel.RequestClose += delegate(System.Object o, System.EventArgs eventArgs)
        {
            mainWindow.Close();
        };


        mainWindow.DataContext = mainWindowViewModel;

        mainWindow.Show();
    }
}

解决方案

There is still the StartupUri lingering in App.xaml i suspect...

这篇关于MainWindow的构造函数获取调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆