我最终采用了几个答案的组合。一开始接受的答案很有用,但正如这里其他人指出的那样,设置Topmost = true
意味着窗口始终在运行的任何其他应用程序之上。我的解决方案是:
var myWindow = new MyWindowType();
myWindow.Owner = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
我最初使用的是:
myWindow.Owner = Application.Current.MainWindow;
然而,如果您像这样打开了三个窗口,则使用此方法会导致问题:
MainWindow
|
-----> ChildWindow1
|
-----> ChildWindow2
设置ChildWindow2.Owner = Application.Current.MainWindow
将把窗口的所有者设置为其祖父窗口,而不是父窗口。
为了加快速度,我已在Visual Studio中添加代码片段。如果您将以下内容添加到工具 --> 代码片段管理器 --> 我的代码片段:
<CodeSnippets
xmlns="http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>MVVM Set owner of page to be current active window</Title>
<Shortcut>owner</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
输入'owner'并双击Tab键,将自动为您添加'
Application.CurrentWindows...
'的部分。