I have the following XAML file which intentionally references an invalid StaticResource style for the label:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ReleaseVsDebugXaml.MainPage">
<Label
Text="Hello, World!"
Style="{StaticResource MissingStyle}"/>
</ContentPage>
If run my app in Debug mode the missing style is silently ignored and the app renders an un-styled label.
If I switch to Release, my app crashes immediately. I have identified the problem as being an uncaught Microsoft.Maui.Controls.Xaml.XamlParseException: StaticResource not found for key MissingStyle
This is incredibly frustrating as it means that simple XAML typos can result in silent errors which will only be caught in release, and furthermore will not produce any callstack or error that is easy to spot.
Of course, I would expect debug to throw at least the same exceptions as release if not more, as to help catch the error. But complaints aside, how can I make debug mode also throw the same exceptions.
I've tried enabling xaml compilation at the application level, although I'm not sure if this is how to properly do so:
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace ReleaseVsDebugXaml
{
public static class MauiProgram
{
...
This did not change the behavior in Debug.
I've also tried to specify that XAML should be compiled on the page that contains the Label with the missing style:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
Unfortunately the exception is still not thrown in Debug mode.
What can I do so that the exception is thrown in Debug mode so that I can catch these problems as I'm coding before it makes it to the QA team?
This is a known issue on GitHub, Missing StaticResource should throw exception also in Debug #15602. This issue has been added to the backlog and you may follow up this issue.
From czmirek's comment, instead of StaticResource
, you may use x:static expression
as an alternative. But you have to move resources to C# code.
public static Style Labelstyle
{
get
{
Style returnStyle = new Style(typeof(Label));
returnStyle.Setters.Add(new Setter { Property=Label.TextColorProperty,Value=Colors.Green});
return returnStyle;
}
}