在WPF中,可以通过设置子窗口的Left和Top属性来控制其位置。以下是一种常见的方法:
<Window x:Class="YourNamespace.ChildWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Child Window" Height="300" Width="400">
<!-- 子窗口内容 -->
</Window>
private void ShowChildWindow()
{
ChildWindow childWindow = new ChildWindow();
// 设置子窗口的位置
double parentLeft = this.Left;
double parentTop = this.Top;
double parentWidth = this.ActualWidth;
double parentHeight = this.ActualHeight;
double childWidth = childWindow.Width;
double childHeight = childWindow.Height;
double childLeft = parentLeft + (parentWidth - childWidth) / 2; // 设置子窗口在父窗口水平居中
double childTop = parentTop + (parentHeight - childHeight) / 2; // 设置子窗口在父窗口垂直居中
childWindow.Left = childLeft;
childWindow.Top = childTop;
childWindow.Owner = this; // 设置子窗口的所有者为父窗口
childWindow.ShowDialog();
}
在上述代码中,我们首先获取父窗口的位置和大小,然后计算子窗口的位置,使其在父窗口中居中显示。最后,将子窗口的所有者设置为父窗口,并调用ShowDialog方法显示子窗口。
这样,子窗口就会在父窗口的中心位置显示出来。
领取专属 10元无门槛券
手把手带您无忧上云