调整大小后 Avalonia 保持 window 位置
Avalonia keep window position after resize
我想在 window 调整大小后保留 window 的位置。例如,JPEGView 如何在更改图像时处理调整大小。
在 WPF 中,这段代码可以完成它:
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
//Calculate half of the offset to move the window
if (sizeInfo.HeightChanged)
Top += (sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height) / 2;
if (sizeInfo.WidthChanged)
Left += (sizeInfo.PreviousSize.Width - sizeInfo.NewSize.Width) / 2;
}
您将如何在 AvaloniaUI 中完成相同的任务?
更新:
我试过订阅 ClientSizeProperty.Changed
,这只会强制 window 在屏幕上居中
ClientSizeProperty.Changed.Subscribe(
x =>
{
var newSize = new Size(
ClientSize.Width + (x.OldValue.Value.Width - x.NewValue.Value.Width) / 2,
ClientSize.Height + (x.OldValue.Value.Height - x.NewValue.Value.Height) / 2);
var rect = new PixelRect(
PixelPoint.Origin,
PixelSize.FromSize(newSize, scaling));
var screen = Screens.ScreenFromPoint(owner?.Position ?? Position);
if (screen != null)
{
Position = screen.WorkingArea.CenterRect(rect).Position;
}
});
我想通了。
ClientSizeProperty.Changed.Subscribe(size =>
{
var x = (size.OldValue.Value.Width - size.NewValue.Value.Width) / 2;
var y = (size.OldValue.Value.Height - size.NewValue.Value.Height) / 2;
Position = new PixelPoint(Position.X + (int)x, Position.Y + (int)y);
});
我想在 window 调整大小后保留 window 的位置。例如,JPEGView 如何在更改图像时处理调整大小。
在 WPF 中,这段代码可以完成它:
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
//Calculate half of the offset to move the window
if (sizeInfo.HeightChanged)
Top += (sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height) / 2;
if (sizeInfo.WidthChanged)
Left += (sizeInfo.PreviousSize.Width - sizeInfo.NewSize.Width) / 2;
}
您将如何在 AvaloniaUI 中完成相同的任务?
更新:
我试过订阅 ClientSizeProperty.Changed
,这只会强制 window 在屏幕上居中
ClientSizeProperty.Changed.Subscribe(
x =>
{
var newSize = new Size(
ClientSize.Width + (x.OldValue.Value.Width - x.NewValue.Value.Width) / 2,
ClientSize.Height + (x.OldValue.Value.Height - x.NewValue.Value.Height) / 2);
var rect = new PixelRect(
PixelPoint.Origin,
PixelSize.FromSize(newSize, scaling));
var screen = Screens.ScreenFromPoint(owner?.Position ?? Position);
if (screen != null)
{
Position = screen.WorkingArea.CenterRect(rect).Position;
}
});
我想通了。
ClientSizeProperty.Changed.Subscribe(size =>
{
var x = (size.OldValue.Value.Width - size.NewValue.Value.Width) / 2;
var y = (size.OldValue.Value.Height - size.NewValue.Value.Height) / 2;
Position = new PixelPoint(Position.X + (int)x, Position.Y + (int)y);
});