Skip to content

Commit

Permalink
Recreate TextLayout on measure to make sure constraint is updated (#1…
Browse files Browse the repository at this point in the history
…4705)

* Recreate TextLayout on measure to make sure constraint is updated

* Add failing test
  • Loading branch information
Gillibald authored and maxkatz6 committed Feb 24, 2024
1 parent 9fcf022 commit 760c674
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/Avalonia.Controls/TextBlock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,6 @@ protected override void OnMeasureInvalidated()
{
_textLayout?.Dispose();
_textLayout = null;

_textRuns = null;

base.OnMeasureInvalidated();
Expand All @@ -690,6 +689,10 @@ protected override Size MeasureOverride(Size availableSize)

_constraint = availableSize.Deflate(padding);

//Reset TextLayout otherwise constraint might be outdated.
_textLayout?.Dispose();
_textLayout = null;

var inlines = Inlines;

if (HasComplexContent)
Expand Down Expand Up @@ -819,15 +822,19 @@ private void OnInlinesChanged(InlineCollection? oldValue, InlineCollection? newV
{
oldValue.LogicalChildren = null;
oldValue.InlineHost = null;
oldValue.Invalidated -= (s, e) => InvalidateMeasure();
oldValue.Invalidated -= Invalidated;
}

if (newValue is not null)
{
newValue.LogicalChildren = LogicalChildren;
newValue.InlineHost = this;
newValue.Invalidated += (s, e) => InvalidateMeasure();
newValue.Invalidated += Invalidated;
}

return;

void Invalidated(object? sender, EventArgs e) => InvalidateMeasure();
}

void IInlineHost.Invalidate()
Expand Down
26 changes: 26 additions & 0 deletions tests/Avalonia.Controls.UnitTests/TextBlockTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,27 @@ public void Default_Text_Value_Should_Be_Null()
Assert.Equal(null, textBlock.Text);
}

[Fact]
public void Calling_Measure_Should_Update_Constraint_And_TextLayout()
{
using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
{
var textBlock = new TestTextBlock { Text = "Hello World" };

textBlock.Measure(new Size(100, 100));

var textLayout = textBlock.TextLayout;

Assert.Equal(new Size(100,100), textBlock.Constraint);

textBlock.Measure(new Size(50, 100));

Assert.Equal(new Size(50, 100), textBlock.Constraint);

Assert.NotEqual(textLayout, textBlock.TextLayout);
}
}

[Fact]
public void Changing_InlinesCollection_Should_Invalidate_Measure()
{
Expand Down Expand Up @@ -328,5 +349,10 @@ public void TextBlock_TextLines_Should_Be_Empty()
Assert.NotEqual(count, count1);
}
}

private class TestTextBlock : TextBlock
{
public Size Constraint => _constraint;
}
}
}

0 comments on commit 760c674

Please sign in to comment.