fix: 在窗口初始化前设置保存的尺寸,消除启动时偏右下偏移 (#9498)

* fix: 在窗口初始化前设置保存的尺寸,消除启动时偏右下偏移

WindowStartupLocation="CenterScreen"(来自 XAML)能正确包含 chrome 居中窗口,
但只能使用生效时的 Width/Height。旧代码在 OnLoaded 中设置保存的尺寸为时已晚
(CenterScreen 已应用),随后又用不含 chrome 的手工计算覆盖 Position,
导致窗口每次启动偏右下。

修复方式:在 Initialized 事件中设置保存的 Width/Height。
Avalonia 中 Initialized 在 Show() 过程中触发,早于 WindowStartupLocation 生效,
因此 CenterScreen 能用正确的保存尺寸居中。

同时移除 OnLoaded 中重复的 Width/Height 设置(Initialized 中已设置)。

* Update WindowBase.cs

---------

Co-authored-by: 2dust <31833384+2dust@users.noreply.github.com>
This commit is contained in:
sparklelcm333
2026-06-07 14:59:50 +08:00
committed by GitHub
parent 5fed566a32
commit 8147b39723

View File

@@ -4,6 +4,7 @@ public class WindowBase<TViewModel> : ReactiveWindow<TViewModel> where TViewMode
{
public WindowBase()
{
Initialized += OnWindowInitialized;
Loaded += OnLoaded;
}
@@ -12,30 +13,33 @@ public class WindowBase<TViewModel> : ReactiveWindow<TViewModel> where TViewMode
throw new NotImplementedException();
}
protected virtual void OnLoaded(object? sender, RoutedEventArgs e)
private void OnWindowInitialized(object? sender, EventArgs e)
{
try
{
var sizeItem = ConfigHandler.GetWindowSizeItem(AppManager.Instance.Config, GetType().Name);
if (sizeItem == null)
if (sizeItem is null)
{
return;
}
Width = sizeItem.Width;
Height = sizeItem.Height;
if (sizeItem.Width > 0 && !Width.Equals(sizeItem.Width))
{
Width = sizeItem.Width;
}
var workingArea = (Screens.ScreenFromWindow(this) ?? Screens.Primary).WorkingArea;
var scaling = (Utils.IsMacOS() ? null : VisualRoot?.RenderScaling) ?? 1.0;
var x = workingArea.X + ((workingArea.Width - (Width * scaling)) / 2);
var y = workingArea.Y + ((workingArea.Height - (Height * scaling)) / 2);
Position = new PixelPoint((int)x, (int)y);
if (sizeItem.Height > 0 && !Height.Equals(sizeItem.Height))
{
Height = sizeItem.Height;
}
}
catch { }
}
protected virtual void OnLoaded(object? sender, RoutedEventArgs e)
{
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);