你怎么中心主窗口中的WPF? [英] How do you center your main window in WPF?

查看:269
本文介绍了你怎么中心主窗口中的WPF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF应用程序,我需要知道如何编程居中WAIN窗口(不XAML)。



我需要能够同时做到这一点在启动和响应于某些用户事件。它必须动态计算,因为窗口大小本身是动态的。



什么是做到这一点最简单的方法?在旧的Win32代码,我会调用系统指标,功能和解决全部问题。现在仍然是这样,它的完成还是有一个简单的 CenterWindowOnScreen()函数现在我可以调用。


解决方案

 私人无效CenterWindowOnScreen()
{
双屏幕宽度= System.Windows.SystemParameters.PrimaryScreenWidth;
双screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
双WINDOWWIDTH = this.Width;
双WINDOWHEIGHT = this.Height;
this.Left =(屏幕宽度/ 2) - (WINDOWWIDTH / 2);
this.Top =(screenHeight / 2) - (WINDOWHEIGHT / 2);
}

您可以使用此方法将窗口位置设置为屏幕的中心


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 to certain user events. It has to be dynamically calculated since the window size itself is dynamic.

What's the simplest way to do this? Under old Win32 code, I'd call the system metrics functions and work it all out. Is that still the way it's done or is there a simple CenterWindowOnScreen() function I can now call.

解决方案

private void CenterWindowOnScreen()
{
    double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
    double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
    double windowWidth = this.Width;
    double windowHeight = this.Height;
    this.Left = (screenWidth / 2) - (windowWidth / 2);
    this.Top = (screenHeight / 2) - (windowHeight / 2);
}

You can use this method to set the window position to the center of your screen.

这篇关于你怎么中心主窗口中的WPF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆