tags:

views:

152

answers:

2

Hi everyone,

i have a serious problem with my WPF Application. I realized a WPF Control Library to use as an Addin in MS Office 2007.

The WPF-Class is instantiated by the host and creates a toolbar with some buttons in MS Office. By clicking a button the wpf window shoud appear. The problem is that i alway recieve the following error: "The calling thread must be STA, because many UI components require this." My main function is marked as [STAThread].

It seems that the button_Click event runs in an other thread than the UI therad.

I tryed 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 tryed to start the window in an seperate sta thread and join the thread, but this didn't work either. 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 seperate thread).

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

Is it posible to determine the ui thread and create a dispatcher for this thread, or how can i come back to the ui thread.

So please help. Thanks for your answers.

+1  A: 

You will need to use the application UI dispatcher. Try using:

Application.Current.Dispatcher.Invoke(...)
DEHAAS
I believe the default name for Application is App in WPF applications.
DEHAAS
Unfortunately Application.Current is null :( Any other ideas?
MarkusEm
A: 

Unfortunately Application.Current is null :( Application.Current works fine in an WPF Application, but i realized a WPF Control Library, and my host is an console application (for testing, but later an MS Project 2007 Addin). Any other ideas?

MarkusEm