我有一个名为ItemControl的用户控件。
public partial class ItemControl : UserControl
{
public ModuloFramework.ItemSystem.Item Item { get; set; }
public ItemControl(ModuloFramework.ItemSystem.Item item)
{
Control.CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
Item = item;
}
private void ItemControl_Load(object sender, System.EventArgs e)
{
itemNameLabel.Text = Item.Name;
itemTypeLabel.Left = itemNameLabel.Right + 5;
itemTypeLabel.Text = Item.Type.ToString();
itemPriceLabel.Left = itemTypeLabel.Right + 5;
itemPriceLabel.Text = Item.Price.ToString();
itemDescriptionLabel.Text = Item.Description;
}
}
我有另一种形式,只是测试其中一种:
public partial class Form1 : Form
{
public List<ModuloFramework.ItemSystem.Item> Items { get; set; }
private Button EscapeButton { get; }
public Form1(List<ModuloFramework.ItemSystem.Item> items)
{
InitializeComponent();
Items = items;
EscapeButton = new Button()
{
Enabled = false,
Visible = false
};
EscapeButton.Click += (sender, args) => Close();
}
private void Form1_Load(object sender, EventArgs e)
{
this.CancelButton = EscapeButton;
int y = 0;
foreach (Item item in Items) {
ItemControl control = new ItemControl(item);
control.Left = 0;
control.Top = y;
y += control.Height + 3;
panel1.Controls.Add(control);
}
}
}
这是表单被调用的上下文:
Task.Run(() =>
{
List<Item> items = new List<Item>()
{
TestItem.Item1,
TestItem.Item2
};
Form1 form = new Form1(items);
form.Show();
});
当我尝试运行它时,会发生的情况是Form1实例打开,它卡住了,而用户控件应该在的地方,它显示了透明的空间,显示了它和游戏表单背后的部分,
几秒钟后,表单就死了。
再次打开表单会导致相同的错误
我在这里做错了什么?
编辑:修复代码,显示在这里,以防有人想查看Erik修复的示例
List<Item> items = new List<Item>()
{
TestItem.Item1,
TestItem.Item2,
TestItem.Item1,
TestItem.Item2
};
Form1 form = new Form1(items);
form.Show();
Thread trd = new Thread(() =>
{
Application.Run(form);
});