How to not open multiple windows in WPF

南楼画角 提交于 2019-12-11 13:25:17

问题


In my WPF application I use this code to open a new windows from a button:

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. How do I code it so it override the previous one that is open, if any.


回答1:


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();    
}



回答2:


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



回答3:


Use ShowDialog() instead of Show() to make the dialog modal (so that you cannot do anything else while the dialog is open).

That also allows you to get the return value, indicating whether the user (i.e.) pressed cancel or ok.




回答4:


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();    
}


来源:https://stackoverflow.com/questions/33263605/how-to-not-open-multiple-windows-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!