From 66a8d1bfe083534ab9d7395417e8e9edf6271ec6 Mon Sep 17 00:00:00 2001 From: Johan Appelgren Date: Sat, 31 May 2025 15:23:13 +0200 Subject: [PATCH] Fix MeasureCore when there's a size constraint and there's a negative margin. (#18462) --- src/Avalonia.Base/Layout/Layoutable.cs | 6 ++-- .../Layout/LayoutableTests.cs | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/Avalonia.Base/Layout/Layoutable.cs b/src/Avalonia.Base/Layout/Layoutable.cs index 47f2217816..fbf278f5d7 100644 --- a/src/Avalonia.Base/Layout/Layoutable.cs +++ b/src/Avalonia.Base/Layout/Layoutable.cs @@ -596,15 +596,15 @@ namespace Avalonia.Layout (width, height) = LayoutHelper.RoundLayoutSizeUp(new Size(width, height), scale); } + width += margin.Left + margin.Right; + height += margin.Top + margin.Bottom; + if (width > availableSize.Width) width = availableSize.Width; if (height > availableSize.Height) height = availableSize.Height; - width += margin.Left + margin.Right; - height += margin.Top + margin.Bottom; - if (width < 0) width = 0; diff --git a/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests.cs b/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests.cs index b8cba8c169..5784c46964 100644 --- a/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests.cs +++ b/tests/Avalonia.Base.UnitTests/Layout/LayoutableTests.cs @@ -435,6 +435,35 @@ namespace Avalonia.Base.UnitTests.Layout }); } + [Fact] + public void Constraint_And_Negative_Margin() + { + using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface); + + var textBlock = new TextBlock + { + Margin = new Thickness(-10), + Text = "Lorem ipsum dolor sit amet", + }; + + var border = new Border + { + MaxWidth = 100, + Child = textBlock, + }; + + border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + border.Arrange(new Rect(default, border.DesiredSize)); + + Assert.Multiple(() => + { + Assert.Equal(new Size(100, 0), border.DesiredSize); + Assert.Equal(new Rect(0, 0, 100, 0), border.Bounds); + Assert.Equal(new Size(100, 0), textBlock.DesiredSize); + Assert.Equal(new Rect(-10, -10, 120, 20), textBlock.Bounds); + }); + } + private class TestLayoutable : Layoutable { public Size ArrangeSize { get; private set; }