0

我有 WPF 用户控件,它需要托管在MTAThread的 Windows 窗体中的 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 中,它抛出异常“调用线程无法访问此对象......”

对此的任何帮助将不胜感激。

4

1 回答 1

0

I'm not completely sure, but most likely the ElementHost Windows-Forms control is a wrapper around a COM/ActiveX-Object.

And as COM/ActiveX UI controls are not thread safe on their own, they have to run in STA appartment. An very well posed explanation can be found here.

So I think, you have no real choice and have to change your entry-thread to STA.

于 2014-01-09T13:21:20.427 回答