Chris
Chris

Reputation: 1015

Bring dialog window to front

I am showing a window on a button click like this:

private void showWindow(object obj)
{
    var dialog = new AddItemView();
    dialog.Show();
}

If the button is clicked again, while this window is still open, how do I bring this window to the front and not create a new one?

Upvotes: 0

Views: 2297

Answers (2)

Jorge Chibante
Jorge Chibante

Reputation: 102

Just a quick sketch but this should do what you want:

Window1 W = new Window1();

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (W.IsVisible)
        W.Activate();
    else
        W.Show();
}

If this does not do it, maybe I have misread your question.

Edited to correct a bug.

Add this on the class constructor where you are instantiating the window. A window cannot be closed after is opened.

        W.Closing += (s, e) => 
        {
            e.Cancel = true;
            ((Window)s).Hide();
        };

Upvotes: 0

grantnz
grantnz

Reputation: 7423

Just store the dialog object and check whether it's already been created in showWindow.

Used the windows Closed event to clear the reference to the dialog object.

AddItemView dialog;

private void showWindow(object obj)
{

    if ( dialog == null )
    {
       dialog = new AddItemView();
       dialog.Show();
       dialog.Owner = this;
       dialog.Closed += new EventHandler(AddItemView_Closed);
    }
    else
       dialog.Activate();
}

void AddItemView_Closed(object sender, EventArgs e)
    {

        dialog = null;
    }

Upvotes: 2

Related Questions