How do you center your main window in WPF?

前端 未结 13 1353
爱一瞬间的悲伤
爱一瞬间的悲伤 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:28

    Rect workArea = System.Windows.SystemParameters.WorkArea;
    this.Left = (workArea.Width - this.Width) / 2 + workArea.Left;
    this.Top = (workArea.Height - this.Height) / 2 + workArea.Top;
    

    This takes into account the taskbar size (by using System.Windows.SystemParameters.WorkArea) and position (by adding workArea.Left and workArea.Top)

提交回复
热议问题