1

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.

4 Answers 4

3

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();    
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

0

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.

1 Comment

Hi @PMF. I already think of that solution, but I have to be able to use my main windows when this window is open.
0

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

6 Comments

Exactly, hence I mentioned it may not be able to be used due to design restrictions however I don't know what he wants his program to do...
well if he wants to click again he definitely wants access isn't ?
He didn't say that, but he said currently that is a possibility
Hi guys thanks for your respons, but I need to be able to use my main window when this current window is open.
see op's comment to PMF's ans, he suggested same thing
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.