你如何在 WPF 中居中你的主窗口? [英] How do you center your main window in WPF?

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

问题描述

我有一个 WPF 应用程序,我需要知道如何以编程方式(不是在 XAML 中)使 wain 窗口居中.

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.

最简单的方法是什么?在旧的 Win32 代码下,我会调用系统度量函数并将其全部解决.这仍然是它完成的方式还是有一个简单的 CenterWindowOnScreen() 函数我现在可以调用.

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天全站免登陆