簡體   English   中英

在表單中切換視圖-使用面板C#

[英]Switch View in form - using panel c#

使用按鈕更改表單項目的視圖。 如您所見,每個按鈕中都會有很多文本。

private void start_Click(object sender, EventArgs e)

    {
      panel1.Visible = true;
      panel2.Visible = false;
      panel3.Visible = false;
      panel4.Visible = false;
    }

因此提出了一種方法。 仍然感覺很笨拙。是否有更好的方法來切換每個面板的視圖?

    private void start_Click(object sender, EventArgs e)
    {
      panel = 1;
      PanelW(1);
    }

    public void PanelW(int panel)
    {
        if (panel == 1)
        {
            panel1.Visible = true;
            panel2.Visible = false;
            panel3.Visible = false;
            panel4.Visible = false;
        }
        else if (panel == 2)
        {
            panel2.Visible = true;
            panel1.Visible = false;
            panel3.Visible = false;
            panel4.Visible = false;
        }
        else if (panel == 3)
        {
            panel3.Visible = true;
            panel1.Visible = false;
            panel2.Visible = false;
            panel4.Visible = false;
        }
        else if (panel == 4)
        {
            panel4.Visible = true;
            panel1.Visible = false;
            panel2.Visible = false;
            panel3.Visible = false;
        }

我不想使用tabcontrol。 不知道是否最好也使用button的返回值,而不是void。

您可以使用多種方式執行此操作,例如:

public void PanelW(int panel)
{
    foreach (var pb in this.Controls.OfType<Panel>())
        pb.Visible = pb.Name == "panel" + panel;
}

或者像這樣使用linq:

public void PanelW(int panel)
{
    Controls.OfType<Panel>().Count(p => (p.Visible = p.Name == "panel" + panel));
}

注意:如果您將面板命名為問題(面板1,面板2,面板3,面板4 ..),則命題1和命題2起作用。

或者只是如果您沒有很多面板

public void PanelW(int panel)
{
    panel1.Visible = panel == 1;
    panel2.Visible = panel == 2;
    panel3.Visible = panel == 3;
    panel4.Visible = panel == 4;
}

有很多方法可以做到這一點。 就在我腦海中,您可以將Panel子類化,並為其添加一個屬性,然后使用for循環基於該屬性設置可見性。 子面板:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

    public enum PanelType
    {
        HomeScreen, Settings
    }
    public partial class CustomPanel : Panel
    {

        public PanelType PanelType { get; set; }

    }
}

然后切換面板的方法:

        private void button1_Click(object sender, EventArgs e)
        {
            SwitchPanel(PanelType.HomeScreen);
        }

        private void SwitchPanel(PanelType displayType)
        {
            foreach (var ctl in this.Controls)
            {
                if (ctl.GetType() == typeof(CustomPanel))
                    ((CustomPanel)ctl).Visible = ((CustomPanel)ctl).PanelType == displayType;
            }
        }

然后,您需要用自定義面板(或任何您稱呼的面板)替換現有面板,然后在設計器中的每個面板上將其設置為面板類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM