简体   繁体   中英

How to get a reference to the Window from a WPF UserControl hosted in a WinForms ElementHost

I have a WPF UserControl that is being hosted on a Windows Form via an ElementHost. Within the WPF UserControl there is a button for editing Items details that opens a new WPF Window.

 EditAlarm view = new EditAlarm();
 view.DataContext = viewModel;
 view.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
 view.ShowDialog();

This works the first time and displays the window. Once the window is closed however clicking the button again throws an error on:

 EditAlarm view = new EditAlarm();

The error given is "The Application object is being shut down." I believe this is because the Application does not have a MainWindow set, so when the Edit Window is displayed it believes it to be the MainWindow so that closing it makes it think the Application is closing too.

To fix this I as going to try the following:

 // In UserControl Constructor
 var window = System.Windows.Window.GetWindow(this);  
 System.Windows.Application.Current.MainWindow = window;

or

 // In Windows Form
 var window = System.Windows.Window.GetWindow(view);  
 System.Windows.Application.Current.MainWindow = window;

However the window reference is always null. How do I get a reference to WindowsForm Window to use as the MainWindow in the WPF app? For a bonus, will this address my issue with trying to open and close new WPF windows inside my WPF Usercontrol?

Thanks!

I ran across this recently despite the fact that I had already explicitly created a Windows.Application object in the constructor of my main form. Your theory is correct. The Application object has a property, ShutdownMode , with a default of OnLastWindowClose . I changed the value to OnExplicitShutdown and the problem went away. Here's the code from my WinForm in VB.

Private Property WPFApplication As Windows.Application

Public Sub New()
    ' This call is required by the Windows Form Designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    If (WPFApplication Is Nothing) Then
        WPFApplication = New Windows.Application
        WPFApplication.ShutdownMode = Windows.ShutdownMode.OnExplicitShutdown
    End If
End Sub

Private Sub frmMain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
    If (WPFApplication IsNot Nothing) Then
        WPFApplication.Shutdown()
    End If
End Sub

You can set the owner of the wpf window with the WindowInteropHelper class

var helper = new WindowInteropHelper(window);
helper.Owner = ownerForm.Handle;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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