Jack Penguin
Jack Penguin

Reputation: 53

XAML window inside winforms program

When I use a button on a form for Winforms to open a window made in XAML the first time it works with no issues, then I close the window and re-click the button, but on the InitializeComponent() for the window being created I get an exception with the message, "The Application object is being shut down".

//code on button press is this 
var rs = new RestoreSettings();
rs.Show();

I have tried hosting it as a user control inside an element host still the same issue.

Upvotes: 1

Views: 223

Answers (1)

György Kőszeg
György Kőszeg

Reputation: 18013

In a normal application both the WinForms and WPF environment is kickstarted by an Application type, which is typically called from the Main method.

Here this does not happen for the WPF environment, which causes problems. If you want to show a WPF window from a WinForms application you need to boot up the dispatcher. Best to do this in a new thread so it can be shut down as many times as you want:

private void ShowWpfWindow()
{
    // This delegate is executed in new thread
    ThreadStart showWindow = () =>
    {
        var window = new RestoreSettingsWindow(); // your window to show

        // making sure that the thread can exit when the window is closed
        window.Closed += (sender, e) => Dispatcher.InvokeShutdown();

        window.Show();

        // Starts the dispatcher in the new thread and does not let the thread exit.
        // This call is returned when the window is closed (due to the Closed event handler)
        System.Windows.Threading.Dispatcher.Run();
    };

    // Creating and starting an STA thread for the WPF window
    Thread wpfThread = new Thread(showWindow);
    wpfThread.SetApartmentState(ApartmentState.STA);
    wpfThread.Priority = ThreadPriority.Normal;
    wpfThread.Start();
}

Upvotes: 2

Related Questions