【问题标题】:How do I decide whether to create a new window when i Click on a button单击按钮时如何决定是否创建新窗口
【发布时间】:2015-07-21 14:45:59
【问题描述】:

我在启动应用程序时出现了一个小窗口 (winReset)。按完成后,主窗口打开。

但是,主窗口包含一个按钮,单击该按钮会再次打开 winReset。这次当你在 winReset 上单击 Done 时,我不想要一个新的 Main Window 实例,这与第一次不同。我只想关闭winReset。

我在这里的代码有问题。

到目前为止,这是我在 winReset 背后的代码中的内容,但它不起作用:

private void btnClickDone(object sender, RoutedEventArgs e)
    {

        Window win = App.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == "main");

        if (win.ShowDialog() == true)
        {

            this.Close();
        }

        else
        {
            MainWindow main = new MainWindow();
            App.Current.MainWindow = main;
            this.Close();
            main.Show();
          }
}

我正在尝试做的是仅在不存在的情况下创建一个新的 MainWindow。如果有,那么只需关闭当前的 winReset。我不确定我为什么要为此苦苦挣扎,但我似乎无法弄清楚。有什么帮助吗?

【问题讨论】:

  • 这很容易解决。重新创建winReset 时,将bool 变量(如showMain)设置为false。一旦此变量为false,点击完成将关闭应用程序。
  • 如何从另一个窗口引用变量?

标签: c# wpf


【解决方案1】:

您可以像这样检查 App.Current.MainWindow:

if (App.Current.MainWindow != null && App.Current.MainWindow.GetType() == typeof(MainWindow))
{
    this.Close();
}
else
{
    MainWindow main = new MainWindow();
    App.Current.MainWindow = main;
    this.Close();
    main.Show();
}

【讨论】:

  • 这样每次你创建一个新的 mainWindow 实例
  • 在if语句之外,如何引用MainWindow?我不能main = App.Current.MainWindow();
  • 你必须转换它的类型。您可以使用 var main = App.Current.MainWindow as MainWindowvar main = (MainWindow)App.Current.MainWindow... 不要将您的 MainWindow 类与 Application 类的 MainWindow 属性混淆,即使它们具有相同的名称。
【解决方案2】:

您可以将 main 创建为本地对象,然后检查它是否为 null..

Private MainWindow _main = null;

然后在处理程序中——

if(_main == null)
    _main = new MainWindow();

App.Current.MainWindow = _main;
this.Close();
_main.Show();

【讨论】:

  • 如果我在我的 MainWindow 中创建 _main,我如何在我的 winReset 窗口中使用它?
  • App Current MainWindow 将引用您的 MainWindow
  • _main = App.Current.MainWindow 需要的地方
  • 实际上,这似乎不起作用。要创建第一个主窗口,它可以工作。但是当我单击按钮并创建一个新的 winReset 时,单击完成后,会出现一个新的 Main 窗口。
  • 您需要在打开弹出窗口之前设置_主窗口并保留对它的引用
【解决方案3】:

当你想遵循你的方法时,这应该适合你:

Window win = App.Current.Windows.OfType<Window>().SingleOrDefault(w => w.DependencyObjectType.Name == "MainWindow");
if (win != null)
{
  this.Close();
}
else
{
  MainWindow main = new MainWindow();
  App.Current.MainWindow = main;
  this.Close();
  main.Show();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多