[英]Dynamically Adding Class of Controls
我無法動態添加在工作時應如下所示的控件類:
添加一個新工具時,它應顯示在工具欄下方的左側面板中。 到目前為止,我很難使它們出現(中間的一個就是我所做的設計)。
這是代碼:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Problem Occurs Here
EquationBox[] EquationBoxArray = new EquationBox[12];
for (int x = 0; x < 12; x++)
{
EquationBoxArray[x] = new EquationBox();
ActiveForm.Controls.Add(EquationBoxArray[x].mainPanel);
ActiveForm.Controls.Add(EquationBoxArray[x].colorPanel);
}
}
private void add_line_Click(object sender, EventArgs e) //Add Line
{
}
private void clear_Click(object sender, EventArgs e) //Clear Lines
{
}
}
public class EquationBox
{
public Panel colorPanel = new Panel();
public Panel mainPanel = new Panel();
public TextBox equationBox = new TextBox();
public CheckBox isVisibleBox = new CheckBox();
public EquationBox()
{
mainPanel.Size = new Size(200, 72);
colorPanel.Size = new Size(33, 72);
mainPanel.Location = new Point(50, 50);
colorPanel.Location = new Point(50, 50);
colorPanel.BackColor = Color.Red;
}
}
問題發生在這里:
//Problem Occurs Here
EquationBox[] EquationBoxArray = new EquationBox[12];
for (int x = 0; x < 12; x++)
{
EquationBoxArray[x] = new EquationBox();
ActiveForm.Controls.Add(EquationBoxArray[x].mainPanel);
ActiveForm.Controls.Add(EquationBoxArray[x].colorPanel);
}
當我運行它時,它返回:
Additional information: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
甚至在這種情況發生之前,EqautionBox都不會出現。
預先感謝,這真的讓我感到困擾。
對於EquationBox的構造函數:
public EquationBox()
{
mainPanel.Size = new Size(200, 72);
colorPanel.Size = new Size(33, 72);
mainPanel.Location = new Point(50, 50);
colorPanel.Location = new Point(50, 50);
colorPanel.BackColor = Color.Red;
}
首先,您的控件出現了,但是mainPanel是重疊的colorPanel,您看不到mainPanel(與表單相同的BG顏色),因此添加了swap首先解決了
EquationBox[] EquationBoxArray = new EquationBox[12];
for (int x = 0; x < 12; x++)
{
EquationBoxArray[x] = new EquationBox();
this.Controls.Add(EquationBoxArray[x].colorPanel);
this.Controls.Add(EquationBoxArray[x].mainPanel);
}
我正在使用this.Controls
,不確定ActiveForm.Controls
部分,也許在構造時,您的Form1
不是活動的,所以發生了錯誤。
附:我建議將colorPanel添加到mainPanel,而僅將mainPanel添加到Form。 正如Steve Wellens所說,UserControl是一個很好的解決方案。
EquationBox
存在各種問題,面板中沒有TextBox和CheckBox。 使它成為UserControl會更容易。
然后使用FlowLayoutPanel進行定位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.