views:

178

answers:

2

Hi,

I was looking something similar with winforms like

// in Form 1
this.Hide();    
Form2 form = new Form2();
form.Show


// in Form 2
// if button pressed, Form 1 will be displayed, while Form 2 will be Hide.

I was trying my luck for FormEventHandler but doesn't know where to start.

Any suggestions/ideas?

+1  A: 

The Visiblity property of a Window can be set to Hidden to hide it. So if you are in Window1:

this.Visibility = Visibility.Hidden;
Window2 win = new Window2();
win.Show();

To show the window again, simply change its Visibility.

Charlie
+2  A: 

(For the purposes of this answer, Form1 and Form2 represent classes inheriting from Windows.Window)

I would recommend one of the following approaches

Approach 1: Keeping Form2 alive and able to show again

In this case, you'll need to make an instance variable on Form1:

private Form2 form2;

In your code to "switch" to Form2, do this:

if(form2 == null)
{
    form2 = new Form2();

    DependencyPropertyDescriptor.FromProperty(Window.VisibilityProperty, 
            typeof(Window)).AddValueChanged(form2, Form2_VisibilityChanged);
}

Hide();

form2.Show();

Then add this function to Form1:

private void Form2_VisiblityChanged(object sender, EventArgs e)
{
    if(form2.Visility == Visibility.Hidden) Show();
}

Now all you need to do is call Hide(); within Form2 to have it switch back to Form1.

Approach 2: Closing Form2 and opening a new instance each time

This is a bit easier, and more in line with what you have:

Form2 form2 = new Form2();

form2.Closed += Form2_Closed;

Hide();

form2.Show();

Similarly, add this function to Form1:

private void Form2_Closed(object sender, EventArgs e)
{
    Show();
}

Now, instead of calling Hide(); in Form2, call Close();

Adam Robinson
will this work the second time around? i mean, doing the implementation multiple times?
eibhrum
Error occured: Object reference not set to an instance of an object. > Form1.Show();
eibhrum
@eibhrum: I've revamped this answer in light of what the code is actually doing.
Adam Robinson
@Sir Adam: used the 2nd approach and it works. Thanks a lot!
eibhrum