我真的不知道我不能这样做
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);
任何聪明的方法都可以让代码样式的树工作吗?
答案 0 :(得分:2)
只需省略ControlCollection
构造函数调用:
Panel panel = new Panel
{
Controls =
{
new Panel
{
Controls =
{
new Label { Text = "Label1" },
new Label { Text = "Label2" }
}
}
}
};
这会将Panel
和Label
子控件添加到ControlCollection
属性返回的现有 Controls
对象中,而不是创建新的ControlCollection
个对象。