【发布时间】:2023-03-20 12:28:01
【问题描述】:
我有一个打开New Window的按钮。
我想让New Window适合里面的动态内容。
然后将其定位为Center,相对于Main Window。所以它遵循Main Window 的位置。
不是WindowStartupLocation.CenterScreen。
这就是我正在使用的。它并不完全正确。
XAML
New Window 最初设置为 900x500,但被 SizeToContent 覆盖。
<Window x:Class="MyProgram.NewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="New Window"
Width="900"
Height="500">
C#
此按钮位于Main Window。
我使用SizeToContent.Width。
newWindow.Width 不使用SizeToContent 的宽度,而是检测XAML 的宽度900。
这会导致New Window 始终偏离中心。
我尝试将XAML 的宽度设置为Auto 或1,但它仍然偏离中心向不同的方向。
我尝试使用double width = Convert.ToInt32(SizeToContent.Width);,但它说宽度是1。
我运行了newWindow.UpdateLayout(),但没有成功。 https://stackoverflow.com/a/2149676/6806643
public static NewWindow newWindow;
private Boolean IsNewWindowOpened = false;
private void btnNeWindow_Click(object sender, RoutedEventArgs e)
{
// Check if Window is already open
if (IsNewWindowOpened) return;
newWindow = new NewWindow(this);
// Only allow 1 Window instance
newWindow.ContentRendered += delegate { IsNewWindowOpened = true; };
newWindow.Closed += delegate { IsNewWindowOpened = false; };
// Keep Window on Top
newWindow.Owner = Window.GetWindow(this);
// Fit Window to Content
newWindow.SizeToContent = SizeToContent.Width;
// Update Layout
newWindow.UpdateLayout()
// Detect which screen we're on
var allScreens = System.Windows.Forms.Screen.AllScreens.ToList();
var thisScreen = allScreens.SingleOrDefault(s => this.Left >= s.WorkingArea.Left && this.Left < s.WorkingArea.Right);
if (thisScreen == null) thisScreen = allScreens.First();
// Position Relative to MainWindow
newWindow.Left = Math.Max((this.Left + (this.Width - newWindow.Width) / 2), thisScreen.WorkingArea.Left);
newWindow.Top = Math.Max((this.Top + (this.Height - newWindow.Height) / 2), thisScreen.WorkingArea.Top);
// Open Window
newWindow.Show();
}
示例
偏心
正确居中
【问题讨论】:
-
可能你也需要计算dpi
-
@EugeneGorbovoy 我无法让它工作,
corner.X总是返回0。它从屏幕上消失。第二个解决方案在整个屏幕上跳跃。 -
@EugeneGorbovoy 经过更多的调整,我得到了stackoverflow.com/a/7045871/6806643 以
SizeToContent.Width为中心。虽然newWindow.Show()在OnContentRendered()之前会导致它在屏幕上出现故障。 -
@EugeneGorbovoy 我通过将定位放置在
Window_Loaded而不是OnContentRendered()中的 newWindow 来解决故障。测试后我会写一个解决方案。