diff --git a/src/Controls/tests/TestCases.HostApp/Issues/Issue14364.cs b/src/Controls/tests/TestCases.HostApp/Issues/Issue14364.cs new file mode 100644 index 000000000000..62a449b327b7 --- /dev/null +++ b/src/Controls/tests/TestCases.HostApp/Issues/Issue14364.cs @@ -0,0 +1,50 @@ +namespace Maui.Controls.Sample.Issues; + +[Issue(IssueTracker.Github, 14364, "Control size properties are not available during Loaded event", PlatformAffected.Android)] +public class Issue14364 : Shell +{ + public Issue14364() + { + ShellContent shellContent = new ShellContent + { + ContentTemplate = new DataTemplate(typeof(Issue14364Page)), + Route = "Issue14364Page" + }; + + Items.Add(shellContent); + } +} + +public class Issue14364Page : ContentPage +{ + public Issue14364Page() + { + var grid = new Grid + { + HeightRequest = 300, + WidthRequest = 200 + }; + + var label = new Label + { + Text = "Size", + AutomationId = "labelSize" + }; + + label.Loaded += Label_Loaded; + + grid.Children.Add(label); + Content = grid; + } + + void Label_Loaded(object sender, EventArgs e) + { + if (sender is Label label) + { + var h1 = label.Height; + var h2 = label.Width; + + label.Text = $"Height: {h1}, Width: {h2}"; + } + } +} diff --git a/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue14364.cs b/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue14364.cs new file mode 100644 index 000000000000..5ee05d881e08 --- /dev/null +++ b/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue14364.cs @@ -0,0 +1,22 @@ +using NUnit.Framework; +using UITest.Appium; +using UITest.Core; + +namespace Microsoft.Maui.TestCases.Tests.Issues; + +public class Issue14364 : _IssuesUITest +{ + public Issue14364(TestDevice testDevice) : base(testDevice) + { + } + + public override string Issue => "Control size properties are not available during Loaded event"; + + [Test] + [Category(UITestCategories.Layout)] + public void SizePropertiesAvailableDuringLoadedEvent() + { + var label = App.WaitForElement("labelSize"); + Assert.That(label.GetText(), Is.Not.EqualTo("Height: -1, Width: -1")); + } +} \ No newline at end of file diff --git a/src/Core/src/Platform/Android/ViewExtensions.cs b/src/Core/src/Platform/Android/ViewExtensions.cs index d65345bc4159..a4517a872d5c 100644 --- a/src/Core/src/Platform/Android/ViewExtensions.cs +++ b/src/Core/src/Platform/Android/ViewExtensions.cs @@ -595,9 +595,17 @@ internal static IDisposable OnLoaded(this View view, Action action) return; } - disposable?.Dispose(); + // Store local reference to allow cancellation inside the Post callback + var localDisposable = disposable; disposable = null; - action(); + view.Post(() => + { + if (view.IsAttachedToWindow && localDisposable is not null) + { + action(); + localDisposable.Dispose(); + } + }); }; view.ViewAttachedToWindow += routedEventHandler;