Skip to content

Commit

Permalink
Return a blank Label when LoadTemplate is null to prevent Hot Reload …
Browse files Browse the repository at this point in the history
…crashes (#3692) Fixes #2526

* Return a blank Label when LoadTemplate is null to prevent HotReload crashes
Fixes #2526

* Update test
  • Loading branch information
hartez authored Dec 14, 2021
1 parent f4bdce3 commit c57858f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/Controls/src/Core/ElementTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ void IElement.RemoveResourcesChangedListener(Action<object, ResourcesChangedEven
public object CreateContent()
{
if (LoadTemplate == null)
throw new InvalidOperationException("LoadTemplate should not be null");
{
// Returning a Label here instead of throwing an exception because HotReload may temporarily be in state
// where the user is creating a template; this keeps everything else (which expects a result from CreateContent)
// from crashing during that time.
return new Label();
}

if (this is DataTemplateSelector)
throw new InvalidOperationException("Cannot call CreateContent directly on a DataTemplateSelector");

Expand Down
9 changes: 9 additions & 0 deletions src/Controls/tests/Core.UnitTests/DataTemplateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,5 +118,14 @@ public void SetValueAndBinding()
};
Assert.That(() => template.CreateContent(), Throws.InstanceOf<InvalidOperationException>());
}

[Test]
public void HotReloadTransitionDoesNotCrash()
{
// Hot Reload may need to create a template while the content portion isn't ready yet
// We need to make sure that a call to CreateContent during that time doesn't crash
var template = new DataTemplate();
Assert.DoesNotThrow(() => template.CreateContent());
}
}
}
3 changes: 2 additions & 1 deletion src/Controls/tests/Xaml.UnitTests/LoaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,8 @@ public void TestEmptyTemplate()
var page = new ContentPage();
page.LoadFromXaml(xaml);
var template = page.Resources["datatemplate"] as Maui.Controls.DataTemplate;
Assert.Throws<InvalidOperationException>(() => template.CreateContent());

Assert.NotNull(template.CreateContent());
}

[Test]
Expand Down

0 comments on commit c57858f

Please sign in to comment.