The*_*mer 4 c# size wpf window
我刚刚用 C# 编写了一个小程序,可以在我的桌面上显示引号。我的问题是将应用程序的窗口居中。要计算所需的窗口位置,我使用以下公式:
Left = (Screen.PrimaryScreen.Bounds.Width - this.ActualWidth) / 2;
Top = (Screen.PrimaryScreen.Bounds.Height - this.ActualHeight) / 2;
Run Code Online (Sandbox Code Playgroud)
不幸的是 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();
}));
}
}
Run Code Online (Sandbox Code Playgroud)
有人能告诉我这里出了什么问题吗?
提前致谢!
我看到您的代码有两个问题。首先,您试图在窗口调整自身大小以容纳更新的文本之前获取窗口的新宽度。换句话说,您获得的是旧宽度(在插入引号之前)而不是新宽度。要强制窗口立即调整大小,请UpdateLayout()
在您的setLocation()
方法之前调用。
第二个问题是你有一个潜在的单位不匹配。WPF 窗口大小以等于 1/96 英寸的布局单位指定(可能是也可能不是像素,具体取决于您的 DPI 设置)。但是以像素为单位查询桌面屏幕分辨率。因此,根据用户的显示设置,您可能会混合单位并最终导致窗口位置不正确。
归档时间: |
|
查看次数: |
2630 次 |
最近记录: |