简体   繁体   English

如何在WPF中不打开多个窗口

[英]How to not open multiple windows in WPF

In my WPF application I use this code to open a new windows from a button: 在我的WPF应用程序中,我使用以下代码通过一个按钮打开一个新窗口:

private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
    LoginDialog dialog = new LoginDialog();
    dialog.Show();    
}

But when there is already a LoginDialog open and I click the LoginBtn again it open a new LoginDialog windows. 但是当已经有一个LoginDialog打开并且我再次单击LoginBtn时,它将打开一个新的LoginDialog窗口。 How do I code it so it override the previous one that is open, if any. 我如何编码它,使其覆盖先前打开的上一个(如果有)。

You can create a local variable of type Login dialog and check if its null 您可以创建“登录”对话框类型的局部变量,并检查其是否为空

LoginDialog _dialog;

private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
    if(_dialog == null)
    {
        _dialog = new LoginDialog();
     }
    _dialog.Show();    
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
    LoginDialog _dialog = Application.Current.Windows.OfType<LoginDialog>().FirstOrDefault() ?? new LoginDialog();
    _dialog.Show();
}

Use ShowDialog() instead of Show() to make the dialog modal (so that you cannot do anything else while the dialog is open). 使用ShowDialog()而不是Show()可以使对话框成为模态(这样,在打开对话框时您将无法执行其他任何操作)。

That also allows you to get the return value, indicating whether the user (ie) pressed cancel or ok. 这也使您可以获取返回值,该值指示用户(即)按下“取消”还是“确定”。

You may not be able to use this due to design restrictions however you could open the new window so that it disables the others. 由于设计限制,您可能无法使用此功能,但是您可以打开新窗口,从而禁用其他窗口。

private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
    LoginDialog dialog = new LoginDialog();
    dialog.ShowDialog();    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM