【发布时间】:2014-01-10 14:59:54
【问题描述】:
我有 WPF 用户控件,它需要托管在 MTAThread 中的 Windows 窗体中。解决方案应该适用于 STAThread 和 MTAThread。而且从技术上讲,在生产环境中无法更改公寓状态。
程序.cs
[MTAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
void Form1_Load(object sender, EventArgs e)
{
Thread t = new Thread(() =>{
host = new ElementHost();
host.Dock = DockStyle.Fill;
uc = new UserControl1();
host.Child = uc;
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
MessageBox.Show(this.Controls.Count.ToString());
//if (this.InvokeRequired)
//{
// this.Invoke((Action)(() => { this.Controls.Add(host); }));
//}
//else
{
this.Controls.Add(host);
}
MessageBox.Show(this.Controls.Count.ToString());
}
在这种情况下,现在主机被添加到控件中,因为计数增加并且它不会在 MTAThread 中引发任何异常。但是 WPF 用户控件没有呈现。但是,在 STAThread 中,它抛出异常“调用线程无法访问此对象....”
对此的任何帮助将不胜感激。
【问题讨论】:
标签: wpf elementhost mta