gpt4 book ai didi

C# WPF 窗口 : Wrong Width and ActualWidth values

转载 作者:行者123 更新时间:2023-12-03 20:18:11 26 4
gpt4 key购买 nike

我刚刚用 C# 编写了一个在我的桌面上显示引号的小程序。我的问题是将应用程序的窗口居中。要计算窗口的所需位置,我使用以下公式:

        Left = (Screen.PrimaryScreen.Bounds.Width - this.ActualWidth) / 2;
Top = (Screen.PrimaryScreen.Bounds.Height - this.ActualHeight) / 2;

不幸的是 this.ActualWidth 和 this.ActualHeight 给出了错误的值,正如您在屏幕截图中看到的那样。 188,4 和 189 而不是 1000(+)。

http://www.directupload.net/file/d/4044/4x2tgadg_png.htm

这是图形用户界面:

http://www.directupload.net/file/d/4044/63rx2sul_png.htm

文本形式的代码:
public partial class QuotePresenter : Window
{
public QuotePresenter()
{
InitializeComponent();
setSize();
}

private void setSize()
{
MaxWidth = Screen.PrimaryScreen.Bounds.Width * 0.8;
MaxHeight = Screen.PrimaryScreen.Bounds.Height * 0.8;
}

private void setLocation()
{
Left = (Screen.PrimaryScreen.Bounds.Width - this.ActualWidth) / 2;
Top = (Screen.PrimaryScreen.Bounds.Height - this.ActualHeight) / 2;

System.Windows.MessageBox.Show("Actual Width: " + this.ActualWidth + "\nWidth: " + this.Width);
}

public void SetQuote(Quotation quote)
{
Dispatcher.Invoke(new Action(() =>
{
tb_content.Text = quote.Content;
tb_author.Text = "- " + quote.Author;

setLocation();
}));
}
}

有人可以告诉我这里出了什么问题吗?

提前致谢!

最佳答案

我发现您的代码有两个问题。首先,您尝试在窗口调整大小以适应更新的文本之前获取窗口的新宽度。换句话说,你得到的是旧的宽度(在你插入引号之前)而不是新的宽度。要强制窗口立即调整大小,请调用 UpdateLayout()在您的 setLocation() 之前方法。

第二个问题是你有一个潜在的单位不匹配。 WPF 窗口大小以等于 1/96 英寸的布局单位指定(可能是也可能不是像素,具体取决于您的 DPI 设置)。但是以像素为单位查询桌面屏幕分辨率。因此,根据用户的显示设置,您可能会混合单位并最终导致窗口的位置不正确。

关于C# WPF 窗口 : Wrong Width and ActualWidth values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31345573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com