开发者

WPF/C#: Proper implementation for closing/hiding the form while new form is opening

I was looking something similar with winforms like

// in Form 1
this.Hide();    
F开发者_运维技巧orm2 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜