简体   繁体   English

WPF 获取 UI 线程,或如何从非 UI 线程显示窗口

[英]WPF Get UI Thread, or how to show a window from NON-UI Thread

I realized a WPF Control Library to use as an Addin in MS Office 2007.我实现了在 MS Office 2007 中用作插件的 WPF 控件库。

The WPF-Class is instantiated by the host and creates a toolbar with some buttons in MS Office. WPF-Class 由宿主实例化,并在 MS Office 中创建一个带有一些按钮的工具栏。 By clicking a button the WPF window should appear.通过单击按钮,WPF 窗口应出现。 The problem is that I always receive the following error: " The calling thread must be STA, because many UI components require this. " My main function is marked as [STAThread].问题是我总是收到以下错误:“调用线程必须是STA,因为很多UI组件都需要这个。 ”我的主函数被标记为[STAThread]。

It seems that the button_Click event runs in an other thread than the UI thread. button_Click 事件似乎在 UI 线程之外的其他线程中运行。

I tried to use a dispatcher, but that didn't work.我尝试使用调度程序,但没有用。

Dispatcher.CurrentDispatcher.Invoke(
               System.Windows.Threading.DispatcherPriority.Normal,
               new Action(
                 delegate()
                 {
    wpfform wf = new wpfform();
    wf.ShowDialog();
     ));

I think the module gets a wrong dispatcher, but I don't know exactly.我认为该模块使用了错误的调度程序,但我不确切知道。 Next I tried to start the window in an separate STA thread and join the thread, but this didn't work either.接下来,我尝试在单独的 STA 线程中启动窗口并加入该线程,但这也不起作用。 As I removed the [STAThread] Attribute from the main function the window started, but i was unable to access office (because i'm in a separate thread).当我从主函数中删除[STAThread]属性时,窗口启动了,但我无法访问 office(因为我在一个单独的线程中)。

Thread workerThread = new Thread(_ShowDialog);
workerThread.SetApartmentState(ApartmentState.STA);
workerThread.Start();
workerThread.Join();

Is it possible to determine the UI thread and create a dispatcher for this thread, or how can I come back to the UI thread?是否可以确定 UI 线程并为此线程创建调度程序,或者如何返回 UI 线程?

You will need to use the application UI dispatcher.您将需要使用应用程序 UI 调度程序。 Try using:尝试使用:

Application.Current.Dispatcher.Invoke(...)

您可以使用 SynchronizationContext,在 stackoverflow 中对此进行了描述:使用 SynchronizationContext 将事件发送回 WinForms 或 WPF 的 UI (您必须在 UI 线程上“捕获”上下文,遗憾的是,该问题的结果是:您应该使用Application.Current.Dispatcher也许你应该看看为什么是空的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM