如何内联初始化控件的ControlCollection控件属性

本文关键字:控件 ControlCollection 属性 初始化 何内联 | 更新日期: 2023-09-27 17:58:48

我不能做这个真的很困扰我

    Panel panel = new Panel()
    {
        Controls = new ControlCollection(this)
        {
            new Panel()
            {
                Controls = new ControlCollection(this)
                {
                    new Label() { Text = "Label1" },
                    new Label() { Text = "Label2" }
                }
            }
        }
    };

因为,在这个特殊的情况下,我得到了Property or indexer 'Control.Controls' cannot be assigned to -- it is read only

相反,我必须做这个

    Panel innerPanel = new Panel();
    innerPanel.Controls.Add(new Label() { Text = "Label1" });
    innerPanel.Controls.Add(new Label() { Text = "Label2" });
    Panel panel = new Panel();
    panel.Controls.Add(innerPanel);

有什么聪明的方法可以让树状代码风格发挥作用吗?

如何内联初始化控件的ControlCollection控件属性

只需省略ControlCollection构造函数调用:

Panel panel = new Panel
{
    Controls =
    {
        new Panel
        {
            Controls =
            {
                new Label { Text = "Label1" },
                new Label { Text = "Label2" }
            }
        }
    }
};

这将把PanelLabel子控件添加到Controls属性返回的现有ControlCollection对象中,而不是创建新的ControlCollection对象。