【问题标题】:Button clicked once按钮单击一次
【发布时间】:2016-10-12 12:11:17
【问题描述】:

按钮打开时选择一次的选项有问题,我做错了什么?

private Boolean buttonWasClicked = false;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        buttonWasClicked = true;



        if ( buttonWasClicked == true)
        {
         new SettingsWindow().Show();
        var test = new SettingsWindow();
        test.Owner = System.Windows.Application.Current.MainWindow;
        test.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        test.Top = this.Top + 20;

        }
        else {

            buttonWasClicked = false;
        }


   }`

【问题讨论】:

  • Winform 还是 ASP.NET?顺便说一句,你想做什么?
  • 在 Visual Studio C# 中使用 WPF
  • 您正在创建SettingsWindow 的两个副本,您可能不希望这样
  • 问题是我不想打开另一个已经打开的窗口
  • 如果你想以对话框的形式打开它,你可以使用OpenDialog:How do make modal dialog in WPF?

标签: c# wpf button


【解决方案1】:

我会避免保留您自己的标志变量并手动管理其设置。例如,如果用户关闭窗口,您如何更改变量以允许再次打开 SettingsWindow?。在这个问题上有一个更强大的基于系统的方法。查看系统提供的信息将帮助您避免在已经打开一个实例之前再次打开设置窗口。

要检查是否已经打开了 SettingsWindow 的实例,您可以使用系统提供的信息以及类似这样的代码

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Check if, in the Application.Current.Windows collection 
    // there is at least one window of type SettingsWindow
    SettingsWindow w = Application.Current.Windows
                                  .OfType<SettingsWindow>()
                                  .FirstOrDefault();

    if(w == null)
    {
        // No window of the type required, open a new one....
        w = new SettingsWindow();
        w.Owner = System.Windows.Application.Current.MainWindow;
        w.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        w.Top = this.Top + 20;
    }

    // Show it NON MODALLY....
    w.Show();
}

Show 的调用立即返回(非模态),因此您的程序照常继续,MainWindow 仍处于活动状态。
相反,如果你想使用模态方法,(意味着在 SettingsWindow 打开之前,你的 MainWindow 中没有任何东西是活动的)你可以简单地创建 SettingsWindow,设置它的 Owner 并最终设置它的 Position,最后调用 ShowDialog(做不要忘记设置 Owner 属性)。这样,您的代码在 ShowDialog 中被阻止,并且在用户关闭刚刚打开的 SettingsWindow 实例之前不会返回。 (你可以删除上面的所有检查)

【讨论】:

  • 谢谢!这也是我要找的东西
【解决方案2】:

很确定这将永远是真的 跟随史蒂夫的出色回答

buttonWasClicked = true;
if (buttonWasClicked == true)
{
   // this will execute every time
}
else 
{
   // this will never execute
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    相关资源
    最近更新 更多