这个问题的反面已经多次回答了。
public static void SetOwner(object activeWindow, object dialog)
{
if (IsWindow(dialog) && IsWindow(activeWindow))
{
(dialog as Window).Owner = (activeWindow as Window);
}
else if (IsForm(dialog) && IsForm(activeWindow))
{
(dialog as Form).Owner = (activeWindow as Form);
}
else if (IsWindow(dialog) && IsForm(activeWindow))
{
var wih = new WindowInteropHelper(dialog as Window);
wih.Owner = (activeWindow as Form).Handle;
}
else if (IsForm(dialog) && IsWindow(activeWindow))
{
var dialogForm = dialog as Form;
var ownerWindow = activeWindow as Window;
// What goes here?
}
}
答案 0 :(得分:3)
您需要创建一个实现WinForms IWin32Window
接口的类并返回WPF窗口的句柄(使用new WindowInteropHelper(window).Handle
),然后将其传递给表单ShowDialog
。
答案 1 :(得分:3)
为了扩展SLaks的答案,这里有一个例子:
public class WpfWindowWrapper : System.Windows.Forms.IWin32Window
{
public WpfWindowWrapper(System.Windows.Window wpfWindow)
{
Handle = new System.Windows.Interop.WindowInteropHelper(wpfWindow).Handle;
}
public IntPtr Handle { get; private set; }
}
可以在WPF窗口的代码隐藏中使用它:
var winForm = new MyWinForm();
winForm.ShowDialog(new WpfWindowWrapper(this));
通过这种方式,Winform对话框充当WPF窗口的正确子级,具有正确的模态行为。