How to get window link from WPF UserControl hosted in WinForms ElementHost

I have a WPF UserFontrol that is hosted on a Windows Form via ElementHost. The WPF UserControl has a button for editing details details that opens a new WPF window.

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

      

This works for the first time and displays a window. As soon as the window is closed, but clicking the button again throws an error:

 EditAlarm view = new EditAlarm();

      

Specified error: "Application object closed". I believe this is because the application does not have a MainWindow set, so when the edit window is displayed, it thinks it is MainWindow, so closing it makes it think the application is closing as well.

To fix this, I'll 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 zero. How do I get a reference to a WindowsForm Window to use as a MainWindow in a WPF application? For a bonus, would this be my problem when trying to open and close new WPF windows inside my WPF custom control?

Thank!

+3


source to share


2 answers


I looked at this recently, even though I already explicitly created the object Windows.Application

in the constructor of my main form. Your theory is correct. The object Application

has a property ShutdownMode

with a default value OnLastWindowClose

. I changed the value to OnExplicitShutdown

and the problem went away. Here is 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

      

+1


source


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



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

      

0


source







All Articles