问题
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