How do you center your main window in WPF?

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

    As a basic solution, you can use the window's StartupLocation property, set it to one of the enum values defined in System.Windows.WindowStartupLocation enumeration, there is one for center of screen:

    _wpfWindow.StartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
    

    Unfortunately it's not always quite so simple; you need to account for multiple monitors, taskbars, etc. The "CenterScreen" option opens the window in the center of the screen that has the mouse cursor. See this SO question for a lot of information, or reference the api.

提交回复
热议问题