2

I have this WPF application in which MainNavigationWindow has registerd events of some other class in its Constructor:

SomeClass obj = new SomeClass(); 
obj.SomeEvent += new EventHandler(SomeEventHandler);

In the EventHandler method I am trying to show another window, like:

SomeWindow window = new SomeWindow();
window.ShowDialog();

But while creating the new object the above exception is thrown. Can anybody please tell me what can the possible problem and how can I resolve it?

Please note that SomeWindow is derived from System.Window only.

Singleton
  • 3,701
  • 3
  • 24
  • 37
munna
  • 229
  • 1
  • 4
  • 14
  • Which exact line is throwing the exception, and what is the message in the exception? – Jon Skeet Nov 25 '10 at 07:30
  • @Jon: SomeWindow window = new SomeWindow(); this line throws the error. Message is: The calling thread must be STA, because many UI components require this. – munna Nov 25 '10 at 07:37
  • Deleted my answer, because it doesn't apply to that specific error, and I assumed it was in ShowDialog. http://stackoverflow.com/questions/2329978/the-calling-thread-must-be-sta-because-many-ui-components-require-this explains what this message means and what to do about it. – Adam Norberg Nov 25 '10 at 07:40

1 Answers1

6

It sounds like the event isn't being raised in the UI thread, and you need to marshal over to the UI thread before creating the window. This is probably as simple as changing your event handler code to:

Action action = () => {
    SomeWindow window = new SomeWindow();
    window.ShowDialog();
};
Dispatcher.BeginInvoke(action);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194