簡體   English   中英

如何將面板的單個實例多次添加到單個 FlowLayoutPanel(C# 桌面應用程序)?

[英]How to add a single instance of Panel multiple time to a single FlowLayoutPanel(C# desktop application)?

我有一個應用程序,我想將面板的單個實例多次添加到單個 FlowLayoutPanel 實例中。 因此,如果我更改單個 Panel 實例的背景顏色,它將對所有視圖生效。

單個實例意味着在整個應用程序中僅存在該確切實例中的一個。 一個控件只能有一個所有者,不能有多個所有者。

因此,單個實例不能與多個所有者一起存在,因此無法執行此操作。

但是,根據您的描述,這也不是必需的。 您不希望單個實例同時讓多個控件以相同的方式運行。 因此,將所有面板存儲在列表或數組中,然后迭代它們並在需要時應用新的背景顏色。 像這樣。

//Create a list on your form level.
private List<Panel> PanelList { get; set; }

//Store a list of Panels.  You can also add them manually.
//Do this after initialisation of your form and all controls are added.
this.PanelList = this.Controls.OfType<Panel>().ToList();

//When required, call this method
private void UpdatePanelBackgroundColor(Color backColor)
{
    foreach (var panel in this.PanelList)
        panel.BackColor = backColor;
}

您可以嘗試以下代碼將面板多次添加到單個 FlowLayoutPanel。

另外,我編寫了更改 FlowLayoutPanel 中背景顏色的代碼。

代碼:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    private Panel CreateNotificationPanel()
    {
        var p = new Panel { BackColor = Color.Red };
        p.Controls.Add(new Button { Text = "Test" });
        return p;
    }
    FlowLayoutPanel flp = new FlowLayoutPanel { Dock = DockStyle.Fill };
    private void Form1_Load(object sender, EventArgs e)
    {
        flp.Controls.Add(CreateNotificationPanel());
        flp.Controls.Add(CreateNotificationPanel());
        flp.Controls.Add(CreateNotificationPanel());
        this.Controls.Add(flp);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var result = flp.Controls.OfType<Panel>().ToList();
        foreach (var item in result)
        {
            item.BackColor = Color.Yellow;
        }
    }
}

結果:

在此處輸入圖片說明

暫無
暫無

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

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