在C#中隐藏/显示Windows窗体面板 [英] Hide/Show Windows Forms panel in C#

查看:444
本文介绍了在C#中隐藏/显示Windows窗体面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在C#中显示/隐藏面板,但是当我单击button1时,我想看到panel1但出现panel2. 当我喜欢button2时,panel2消失了. 但是当我第一次在button2上点赞时,panel2没有出现. 我不知道我的代码有什么问题,但这是:

I try to show/hide panels in C#, but when I clicked on button1 I wanted to see panel1 but panel2 appeared. And when I cliked on button2, panel2 dissappeared. But when I cliked first on button2, panel2 didn't appear. I don't know what is wrong with my code but here it is:

public Form3()
    {
        InitializeComponent();
    }

    bool show1;
    bool show2;
    private void button1_Click(object sender, EventArgs e)
    {
        if(show1)
        {
            panel1.Visible = false;
            show1 = false;
        }
        else
        {
            panel1.Visible = true;
            show1 = true;
        }
        Application.DoEvents();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (!show2)
        {
            panel2.Visible = true;
            show2 = true;
        }
        else
        {
            panel2.Visible = false;
            show2 = false;
        }
        Application.DoEvents();
    }

推荐答案

不要使用标志,因为您的按钮行为将由标志的状态决定.

Don't use flags, because your button behavior will be determined by the states of the flags.

最好是按照您想要的方式对其进行编码.如果希望每个Button都使相应的面板可见,而其他面板不可见:

Best is to code it the way you want. If you want each Button to make the corresponding panel visible while other panel invisible:

private void button1_Click(object sender, EventArgs e)
{
     panel1.Visible = true;
     panel2.Visible = false;
     //Application.DoEvents();
}

private void button2_Click(object sender, EventArgs e)
{
     panel2.Visible = true;
     panel1.Visible = false;
     //Application.DoEvents();
}

或者,如果您希望每个按钮独立控制每个面板的可见性,请执行以下操作:

Or, if you want each button to control the visibility of each panel independently, do this:

private void button1_Click(object sender, EventArgs e)
{
     panel1.Visible = !panel1.Visible;
     //Application.DoEvents();
}

private void button2_Click(object sender, EventArgs e)
{
     panel2.Visible = !panel2.Visible;
     //Application.DoEvents();
}

最后,可以删除Application.DoEvents()(向 Thorsten Dittmar 贷记),因为控件将立即返回无论如何,在Click方法完成后将其添加到UI线程.阅读他的评论和引用的

Lastly, the Application.DoEvents() can be removed (credit to Thorsten Dittmar) as the control will immediately back to UI thread after the Click method finishes anyway. Read his comment and the referred link.

这篇关于在C#中隐藏/显示Windows窗体面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆