WPF ShowDialog and ElementHost

2019-06-20 09:42发布

问题:

is it possible to display a Modal Window from a WPF User Control, that is a child of an ElementHost, and set the owner/parent of the Modal Window to the containing Form control?

I'm guessing you can't do this, as the Owner property takes an instance of Window, where as I want to set it to the parent of the Element Host control, which is an old Windows Forms Form control. Just wondering if there is a work around or alternative approach.

The problem is when the Modal Window is displayed and the user switches to another application, then back again, the Modal Window is hidden and the user is unable to interact with the main Window. This is due to Windows thinking the Modal Window is still displayed, when it isn't, as there is no Owner/Parent relationship set.

Cheers, James.

回答1:

I'm using WindowInteropHelper to solve that problem like this:

var wpfDialog = new MyWpfDialog();
var interopHelper = new WindowInteropHelper(wpfDialog)  
        {
            Owner = winFormsDialog.Handle
        };

wpfDialog.ShowDialog();


回答2:

I know this post is old, but I came across a way to find the winform window that is hosting the ElementHost from the context of a wpf UserControl where you may not have access to the winform window. I found this to be useful so that I don't have to pass the host window around.


HwndSource winformWindow = (System.Windows.Interop.HwndSource.FromDependencyObject(wpfControlInElementHost) as System.Windows.Interop.HwndSource);
if (winformWindow != null)
{
   var interopHelper = new WindowInteropHelper(wpfWindow)
   {
      Owner = winformWindow.Handle
   };
}


回答3:

Ok just found the solution using WindowInteropHelper.

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/44c903fb-9514-401c-ba85-58acd5293c1b