How do you center your main window in WPF?

前端 未结 13 1348
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 07:07

I have a WPF application and I need to know how to center the wain window programatically (not in XAML).

I need to be able to do this both at startup and in response

13条回答
  •  一整个雨季
    2020-11-28 07:21

    Based on @Wild_A answer I just subscribed to the SizeChanged event, and added this event handler:

    private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        try
        {
            Rect workArea = SystemParameters.WorkArea;
            this.Left = (workArea.Width - e.NewSize.Width) / 2 + workArea.Left;
            this.Top = (workArea.Height - e.NewSize.Height) / 2 + workArea.Top;
        }
        catch (Exception ex) { ... Handel exception; }
    }
    

提交回复
热议问题