munna
munna

Reputation: 229

InvalidOperationException thrown while trying to open new Window

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.

Upvotes: 2

Views: 2429

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500105

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);

Upvotes: 6

Related Questions