如果您的点击命令处理程序位于主窗口后面的代码中,那么您需要设置
deviceSettingWindow.Owner = this;
https://docs.microsoft.com/en-us/dotnet/api/system.windows.window.owner?view=netframework-4.8
这是一个小例子。它包括一个带有处理程序的按钮,其代码在后面的代码中 -
<Window x:Class="MainWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ChildWindow"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="114,137,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
代码隐藏:
using System.Windows;
namespace MainWindow
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var childWindow = new ChildWindow.Window1();
childWindow.Owner = this;
childWindow.Show();
}
}
}
子窗口 - 只是一个空窗口
<Window x:Class="ChildWindow.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ChildWindow"
mc:Ignorable="d"
Title="Window1" Height="450" Width="800">
<Grid>
</Grid>
</Window>
子窗口代码隐藏
using System.Windows;
namespace ChildWindow
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
}
在我的示例中,由于您在 MainWindow 后面的代码中,this 是对 MainWindow 的引用,并且设置 'childWindow.Owner = this' 会将 childWindow 的所有者设置为 MainWindow,这是我所相信的你想要的。
让我有点困惑的是,您在后面的代码中使用了命令和对事件处理程序的引用。我很确定那是行不通的。命令需要绑定到 ICommand 引用 - 您必须实现自己的 ICommand 类,或者使用来自 MVVM Light 或另一个 WPF MVVM 框架的一个。一旦你得到它,你可以通过命令从父窗口传递一个引用作为命令参数。有关如何执行此操作的示例,请参阅passing the current Window as a CommandParameter
如果您在控件上使用事件处理程序,那么它可以绑定到后面代码中的事件处理程序实现,就像我的示例中一样。您需要选择其中一个。
如果您能够提供有关您的设置方式的更多详细信息,我可以更轻松地提供有关您需要走哪条路的意见。