【问题标题】:How to add a single instance of Panel multiple time to a single FlowLayoutPanel(C# desktop application)?如何将单个 Panel 实例多次添加到单个 FlowLayoutPanel(C# 桌面应用程序)?
【发布时间】:2020-07-09 00:27:39
【问题描述】:

我有一个应用程序,我想将 Panel 的单个实例多次添加到单个 FlowLayoutPanel 实例中。因此,如果我更改单个 Panel 实例的背景颜色,它将对所有视图生效。

【问题讨论】:

  • 我不喜欢 FlowLayoutPanel,因为它的属性有限。您可以使用常规面板做更多事情,并在其中添加您自己的面板数组。
  • 如果您分享了一小部分代码,您会收到更准确的答案。

标签: c# .net visual-studio desktop-application


【解决方案1】:

单个实例意味着整个应用程序中只存在一个确切的实例。 一个控件只能有一个所有者,不能有多个。

因此,单个实例不能与多个所有者一起存在,因此不可能这样做。

但是,根据您的描述,这也不是必需的。您不希望单个实例让多个控件同时以相同的方式运行。因此,将所有面板存储在列表或数组中,然后遍历它们并在需要时应用新的背景颜色。像这样。

//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 中多次呈现。
  • @NishantKathiriya 是的,我明白你想要什么。但是为了让一个实例被多次渲染,它必须有多个所有者!
  • 我已按照您的建议实施了面板。但现在的问题是,如果将超过 500 个面板添加到单个 flowLayoutPanel 中,不仅应用程序在渲染时卡住,而且整个笔记本电脑都会挂起,我必须强制关机。关于如何解决这个问题的任何想法。
  • 顺便说一下,我只需要将空面板添加到 flowLayoutPanel。面板内不会有任何控件。此面板仅用于可视化。
  • @NishantKathiriya 你在使用 SuspendLayout() 吗?否则,提出另一个问题。
【解决方案2】:

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

结果:

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多