C# WPF窗口:宽度错误和实际宽度值

4
我刚刚用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

这里是GUI:

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();
        }));
    }
}

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

提前感谢!


我复制了这段代码,删除了所有自定义类,但无法复制您的结果。 - oppassum
"SetQuote" 函数是从另一个线程调用的 - 这可能会导致这些错误吗? - TheFlamer
当我将“setLocation”放在Dispatcher.Invoke之外时,我会得到一个“InvalidOperationException” - 调用线程无法访问此对象,因为不同的线程拥有它。代码的这一行是:Left =(Screen.PrimaryScreen.Bounds.Width - this.ActualWidth)/ 2; - TheFlamer
不,Dispatcher.Invoke() 方法会调用分发器线程,因此它是在 UI 线程上被调用的。 - oppassum
我有两个GUI,一个是带有设置和其他东西的MainWindow,另一个是QuotePresenter。MainWindow创建了一个名为“presentQuotes”的线程,该线程调用了QuotePresenter.setQuote(...),因此实际上我有3个线程,但这可能没有任何区别^^ - TheFlamer
显示剩余2条评论
1个回答

5
我看到你的代码存在两个问题。首先,你试图在窗口调整大小以适应更新后的文本之前获取新宽度。换句话说,你正在获取旧宽度(在插入引用之前)而不是新宽度。为了立即强制窗口重新调整大小,请在setLocation()方法之前调用UpdateLayout()
第二个问题是你有潜在的单位不匹配。WPF窗口尺寸以每英寸96个布局单位为指定(可能是像素,也可能是根据DPI设置而定)。但是桌面屏幕分辨率是以像素为查询单位。因此,根据用户的显示设置,你可能会混合使用单位,并得出不正确的窗口位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接