Reputation: 1697
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.
Upvotes: 1
Views: 793
Reputation: 1073
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
LoginDialog _dialog = Application.Current.Windows.OfType<LoginDialog>().FirstOrDefault() ?? new LoginDialog();
_dialog.Show();
}
Upvotes: 3
Reputation: 4116
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();
}
Upvotes: 3
Reputation: 1627
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();
}
Upvotes: 0
Reputation: 17238
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.
Upvotes: 0