首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在WPF中设置子窗口的位置而不是所有者窗口的中心[已解决!]

在WPF中,可以通过设置子窗口的Left和Top属性来控制其位置。以下是一种常见的方法:

  1. 首先,在XAML中创建一个子窗口(例如,命名为ChildWindow):
代码语言:txt
复制
<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>
  1. 在父窗口的代码中,创建并显示子窗口:
代码语言:txt
复制
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方法显示子窗口。

这样,子窗口就会在父窗口的中心位置显示出来。

对于WPF中设置子窗口位置的更多详细信息,您可以参考以下链接:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券