简体   繁体   English

如何将面板的单个实例多次添加到单个 FlowLayoutPanel(C# 桌面应用程序)?

[英]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.我有一个应用程序,我想将面板的单个实例多次添加到单个 FlowLayoutPanel 实例中。 So that if I change a background color of a single Panel instance than it will take effect on all view.因此,如果我更改单个 Panel 实例的背景颜色,它将对所有视图生效。

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.您可以尝试以下代码将面板多次添加到单个 FlowLayoutPanel。

Also, I make the code that change the back color in the FlowLayoutPanel.另外,我编写了更改 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:结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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