WPF : How to set a Dialog position to show at the center of the application?

前端 未结 14 2545
天命终不由人
天命终不由人 2020-12-02 16:18

How to set Dialog\'s position that came from .ShowDialog(); to show at the center of the mainWindows.

This is the way I try to set position.

         


        
相关标签:
14条回答
  • 2020-12-02 17:07

    This code works if you don't want to use the WindowStartupLocation property in xaml:

    private void CenterWindowOnApplication()
    {
        System.Windows.Application curApp = System.Windows.Application.Current;
        Window mainWindow = curApp.MainWindow;
        if (mainWindow.WindowState == WindowState.Maximized)
        {
            // Get the mainWindow's screen:
            var screen = System.Windows.Forms.Screen.FromRectangle(new System.Drawing.Rectangle((int)mainWindow.Left, (int)mainWindow.Top, (int)mainWindow.Width, (int)mainWindow.Height));
            double screenWidth = screen.WorkingArea.Width;
            double screenHeight = screen.WorkingArea.Height;
            double popupwindowWidth = this.Width;
            double popupwindowHeight = this.Height;
            this.Left = (screenWidth / 2) - (popupwindowWidth / 2);
            this.Top = (screenHeight / 2) - (popupwindowHeight / 2);
        }
        else
        {
            this.Left = mainWindow.Left + ((mainWindow.ActualWidth - this.ActualWidth) / 2;
            this.Top = mainWindow.Top + ((mainWindow.ActualHeight - this.ActualHeight) / 2);
        }
    }
    

    I am using "screen.WorkingArea" because the task bar makes the mainWindow smaller. If you want to place the window in the middle of the screen, you can use "screen.Bounds" instead.

    0 讨论(0)
  • 2020-12-02 17:12

    In the XAML belonging to the Dialog:

    <Window ... WindowStartupLocation="CenterOwner">
    

    and in C# when you instantiate the Dialog:

    MyDlg dlg = new MyDlg();
    dlg.Owner = this;
    
    if (dlg.ShowDialog() == true)
    {
        ...
    
    0 讨论(0)
提交回复
热议问题