C# WPF Window: 错误的宽度和实际宽度值
C# WPF Window: Wrong Width and ActualWidth values
我刚刚用 C# 编写了一个小程序,可以在我的桌面上显示引文。我的问题是将应用程序的 window 居中。要计算 window 的所需位置,我使用以下公式:
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();
}));
}
}
有人能告诉我这里出了什么问题吗?
提前致谢!
我发现您的代码有两个问题。首先,您试图在 window 调整自身大小以适应更新后的文本之前获取其新宽度。换句话说,您得到的是 old 宽度(在插入引号之前)而不是新宽度。要强制 window 立即调整自身大小,请在 setLocation()
方法之前调用 UpdateLayout()
。
第二个问题是您的单位可能不匹配。 WPF window 大小以等于 1/96 英寸的布局单位指定(可能是也可能不是像素,具体取决于您的 DPI 设置)。但是桌面屏幕分辨率是以像素为单位查询的。因此,根据您的用户的显示设置,您可能会混合单位并最终得到 window.
的错误位置
我刚刚用 C# 编写了一个小程序,可以在我的桌面上显示引文。我的问题是将应用程序的 window 居中。要计算 window 的所需位置,我使用以下公式:
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();
}));
}
}
有人能告诉我这里出了什么问题吗?
提前致谢!
我发现您的代码有两个问题。首先,您试图在 window 调整自身大小以适应更新后的文本之前获取其新宽度。换句话说,您得到的是 old 宽度(在插入引号之前)而不是新宽度。要强制 window 立即调整自身大小,请在 setLocation()
方法之前调用 UpdateLayout()
。
第二个问题是您的单位可能不匹配。 WPF window 大小以等于 1/96 英寸的布局单位指定(可能是也可能不是像素,具体取决于您的 DPI 设置)。但是桌面屏幕分辨率是以像素为单位查询的。因此,根据您的用户的显示设置,您可能会混合单位并最终得到 window.
的错误位置