C# WPF 子窗口显示在父窗口中间

父窗口:

<Window x:Class="子窗口显示在父窗口中间.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:子窗口显示在父窗口中间"
         mc:Ignorable="d"
         Title="MainWindow" Height="350" Width="525">
     <Grid>
         <Button Width="120" Height="40" Content="show childwindow" Click="Button_Click"/>
     </Grid>
</Window>

.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 子窗口显示在父窗口中间
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            double[] d = new double[2];
            d[0] = this.Top + this.Height / 2;
            d[1] = this.Left + this.Width / 2;
            ChildWindow cw = new ChildWindow();
            cw.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;
            cw.Top = d[0] - cw.Height / 2;
            cw.Left = d[1] - cw.Width / 2;
            cw.Show();
        }
    }
}

子窗口:

<Window x:Class="子窗口显示在父窗口中间.ChildWindow"
        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:子窗口显示在父窗口中间"
        mc:Ignorable="d"
        Title="ChildWindow" Height="80" Width="300">
    <Grid>
        <TextBlock Text="This is Child Window!" FontSize="20"/>
    </Grid>
</Window>

效果:

 

posted @ 2022-07-12 15:01  羽小兮  阅读(1791)  评论(0)    收藏  举报