简体   繁体   中英

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

I have an application where i would like to add single instance of a Panel multiple time to a single FlowLayoutPanel instance. So that if I change a background color of a single Panel instance than it will take effect on all view.

A Single instance means that only one of that exact instance exists in the whole application. A control can only have a single owner, not multiple.

As such, then a single instance can not exist with multiple owners, so it is not possible to do this.

However, based on what you describe then this is also not necessary. You don't want a single instance what you want is for multiple controls to behave in the same way at the same time. So store all the Panels in a List or Array and then iterate over them and apply the new background colour when required. Like this.

//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;
}

You can try the following code to add a panel many times to a single FlowLayoutPanel.

Also, I make the code that change the back color in the FlowLayoutPanel.

Code:

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;
        }
    }
}

Result:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM