Skip to content

Instantly share code, notes, and snippets.

@StephaneDelcroix
Last active February 1, 2026 21:28
Show Gist options
  • Select an option

  • Save StephaneDelcroix/20ce604f4f4ac38bda93a2f58ab80c60 to your computer and use it in GitHub Desktop.

Select an option

Save StephaneDelcroix/20ce604f4f4ac38bda93a2f58ab80c60 to your computer and use it in GitHub Desktop.
Lazy ResourceDictionary SourceGen Example - MAUI resources created on-demand via AddFactory
<?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="Microsoft.Maui.Controls.Xaml.UnitTests.LazyResourceDictionary">
<ContentPage.Resources>
<Color x:Key="PrimaryColor">Blue</Color>
<Thickness x:Key="StandardPadding">10</Thickness>
<Style x:Key="MyLabelStyle" TargetType="Label">
<Setter Property="TextColor" Value="{StaticResource PrimaryColor}"/>
</Style>
<!-- x:Shared="false" means each access returns a new instance -->
<x:Object x:Key="Handle" x:Shared="false"/>
<!-- Implicit style - applies to all Buttons automatically -->
<Style TargetType="Button">
<Setter Property="BackgroundColor" Value="Green"/>
<Setter Property="Padding" Value="{StaticResource StandardPadding}"/>
</Style>
</ContentPage.Resources>
<StackLayout>
<Label x:Name="label1" Text="Test Label" Style="{StaticResource MyLabelStyle}"/>
</StackLayout>
</ContentPage>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a .NET MAUI source generator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS0219 // Variable is assigned but its value is never used
namespace Microsoft.Maui.Controls.Xaml.UnitTests;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Maui.Controls.SourceGen, Version=10.0.0.0, Culture=neutral, PublicKeyToken=null", "10.0.0.0")]
public partial class LazyResourceDictionary
{
private partial void InitializeComponentSourceGen()
{
// Fallback to Runtime inflation if the page was updated by HotReload
static string? getPathForType(global::System.Type type)
{
var assembly = type.Assembly;
foreach (var xria in global::System.Reflection.CustomAttributeExtensions.GetCustomAttributes<global::Microsoft.Maui.Controls.Xaml.XamlResourceIdAttribute>(assembly))
{
if (xria.Type == type)
return xria.Path;
}
return null;
}
var rlr = global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceProvider2?.Invoke(new global::Microsoft.Maui.Controls.Internals.ResourceLoader.ResourceLoadingQuery
{
AssemblyName = typeof(global::Microsoft.Maui.Controls.Xaml.UnitTests.LazyResourceDictionary).Assembly.GetName(),
ResourcePath = getPathForType(typeof(global::Microsoft.Maui.Controls.Xaml.UnitTests.LazyResourceDictionary)),
Instance = this,
});
if (rlr?.ResourceContent != null)
{
this.InitializeComponentRuntime();
return;
}
var thickness = new global::Microsoft.Maui.Thickness(10);
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(thickness!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 8, 10);
var staticResourceExtension = new global::Microsoft.Maui.Controls.Xaml.StaticResourceExtension();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(staticResourceExtension!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 22, 50);
var label = new global::Microsoft.Maui.Controls.Label();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(label!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 22, 10);
var stackLayout = new global::Microsoft.Maui.Controls.StackLayout();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(stackLayout!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 21, 6);
var __root = this;
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(__root!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 2, 2);
#if !_MAUIXAML_SG_NAMESCOPE_DISABLE
global::Microsoft.Maui.Controls.Internals.INameScope iNameScope = global::Microsoft.Maui.Controls.Internals.NameScope.GetNameScope(__root) ?? new global::Microsoft.Maui.Controls.Internals.NameScope();
#endif
#if !_MAUIXAML_SG_NAMESCOPE_DISABLE
global::Microsoft.Maui.Controls.Internals.NameScope.SetNameScope(__root, iNameScope);
#endif
#if !_MAUIXAML_SG_NAMESCOPE_DISABLE
stackLayout.transientNamescope = iNameScope;
#endif
#if !_MAUIXAML_SG_NAMESCOPE_DISABLE
label.transientNamescope = iNameScope;
#endif
#if !_MAUIXAML_SG_NAMESCOPE_DISABLE
iNameScope.RegisterName("label1", label);
#endif
label.StyleId ??= "label1";
this.label1 = label;
__root.Resources.AddFactory("PrimaryColor", () =>
{
var color = global::Microsoft.Maui.Graphics.Colors.Blue;
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(color!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 7, 10);
return color;
}, shared: true);
var resourceDictionary = __root.Resources;
resourceDictionary["StandardPadding"] = thickness;
__root.Resources.AddFactory("MyLabelStyle", () =>
{
var staticResourceExtension1 = new global::Microsoft.Maui.Controls.Xaml.StaticResourceExtension();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(staticResourceExtension1!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 10, 42);
var setter = new global::Microsoft.Maui.Controls.Setter();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(setter!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 10, 14);
var style1 = new global::Microsoft.Maui.Controls.Style(typeof(global::Microsoft.Maui.Controls.Label));
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(style1!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 9, 10);
setter.Property = global::Microsoft.Maui.Controls.Label.TextColorProperty;
staticResourceExtension1.Key = "PrimaryColor";
var color1 = (global::Microsoft.Maui.Graphics.Color)__root.Resources["PrimaryColor"];
if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(color1!) == null)
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(color1!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 10, 42);
setter.Value = (object)color1;
var setter1 = new global::Microsoft.Maui.Controls.Setter {Property = global::Microsoft.Maui.Controls.Label.TextColorProperty, Value = color1};
if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(setter1!) == null)
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(setter1!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 10, 14);
((global::System.Collections.Generic.ICollection<global::Microsoft.Maui.Controls.Setter>)style1.Setters).Add((global::Microsoft.Maui.Controls.Setter)setter1);
return style1;
}, shared: true);
__root.Resources.AddFactory("Handle", () =>
{
var object0 = new object();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(object0!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 13, 10);
return object0;
}, shared: false);
__root.Resources.AddFactory(typeof(global::Microsoft.Maui.Controls.Button), () =>
{
var staticResourceExtension2 = new global::Microsoft.Maui.Controls.Xaml.StaticResourceExtension();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(staticResourceExtension2!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 17, 40);
var setter2 = new global::Microsoft.Maui.Controls.Setter();
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(setter2!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 17, 14);
var style3 = new global::Microsoft.Maui.Controls.Style(typeof(global::Microsoft.Maui.Controls.Button));
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(style3!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 15, 10);
var setter3 = new global::Microsoft.Maui.Controls.Setter {Property = global::Microsoft.Maui.Controls.VisualElement.BackgroundColorProperty, Value = global::Microsoft.Maui.Graphics.Colors.Green};
if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(setter3!) == null)
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(setter3!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 16, 14);
((global::System.Collections.Generic.ICollection<global::Microsoft.Maui.Controls.Setter>)style3.Setters).Add((global::Microsoft.Maui.Controls.Setter)setter3);
setter2.Property = global::Microsoft.Maui.Controls.Button.PaddingProperty;
staticResourceExtension2.Key = "StandardPadding";
var thickness1 = thickness;
if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(thickness1!) == null)
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(thickness1!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 17, 40);
setter2.Value = (object)thickness1;
var setter4 = new global::Microsoft.Maui.Controls.Setter {Property = global::Microsoft.Maui.Controls.Button.PaddingProperty, Value = thickness1};
if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(setter4!) == null)
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(setter4!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 17, 14);
((global::System.Collections.Generic.ICollection<global::Microsoft.Maui.Controls.Setter>)style3.Setters).Add((global::Microsoft.Maui.Controls.Setter)setter4);
return style3;
}, shared: true);
label.SetValue(global::Microsoft.Maui.Controls.Label.TextProperty, "Test Label");
staticResourceExtension.Key = "MyLabelStyle";
var style4 = (global::Microsoft.Maui.Controls.Style)__root.Resources["MyLabelStyle"];
if (global::Microsoft.Maui.VisualDiagnostics.GetSourceInfo(style4!) == null)
global::Microsoft.Maui.VisualDiagnostics.RegisterSourceInfo(style4!, new global::System.Uri(@"Issues/LazyResourceDictionary.sgen.xaml;assembly=Microsoft.Maui.Controls.Xaml.UnitTests", global::System.UriKind.Relative), 22, 50);
label.SetValue(global::Microsoft.Maui.Controls.VisualElement.StyleProperty, style4);
((global::System.Collections.Generic.ICollection<global::Microsoft.Maui.IView>)stackLayout.Children).Add((global::Microsoft.Maui.IView)label);
__root.SetValue(global::Microsoft.Maui.Controls.ContentPage.ContentProperty, stackLayout);
}
}
using Microsoft.Maui.Controls.Shapes;
using Microsoft.Maui.Graphics;
using Xunit;
namespace Microsoft.Maui.Controls.Xaml.UnitTests;
public partial class LazyResourceDictionary : ContentPage
{
public LazyResourceDictionary() => InitializeComponent();
[Collection("Xaml Inflation")]
public class Tests
{
[Fact]
public void SharedResourceReturnsSameInstance()
{
// This test only works with SourceGen (the only inflator that supports LazyRD)
var page = new LazyResourceDictionary();
// Verify keyed style resource is accessible
Assert.True(page.Resources.TryGetValue("MyLabelStyle", out var style));
Assert.IsType<Style>(style);
Assert.Equal(typeof(Label), ((Style)style).TargetType);
// Accessing the same key returns the same instance (shared=true is default)
Assert.True(page.Resources.TryGetValue("MyLabelStyle", out var style2));
Assert.Same(style, style2);
}
[Fact]
public void NamedElementsStillWork()
{
var page = new LazyResourceDictionary();
// Verify named elements work
Assert.NotNull(page.label1);
Assert.Equal("Test Label", page.label1.Text);
}
[Fact]
public void StaticResourceBindingWorks()
{
var page = new LazyResourceDictionary();
// Verify the label has the style applied via StaticResource
Assert.NotNull(page.label1.Style);
Assert.Equal(typeof(Label), page.label1.Style.TargetType);
}
[Fact]
public void ColorResourceWorks()
{
var page = new LazyResourceDictionary();
// Verify color resource is accessible (lazy)
Assert.True(page.Resources.TryGetValue("PrimaryColor", out var color));
Assert.IsType<Color>(color);
Assert.Equal(Colors.Blue, color);
}
[Fact]
public void ImplicitStyleIsInResourceDictionary()
{
var page = new LazyResourceDictionary();
// Verify implicit style is in the resource dictionary
// Implicit styles use the TargetType.FullName as the key
Assert.True(page.Resources.TryGetValue(typeof(Button).FullName, out var implicitStyle));
Assert.IsType<Style>(implicitStyle);
Assert.Equal(typeof(Button), ((Style)implicitStyle).TargetType);
}
[Fact]
public void NonSharedResourceReturnsNewInstanceEachTime()
{
var page = new LazyResourceDictionary();
// Access the x:Shared="false" resource multiple times
Assert.True(page.Resources.TryGetValue("Handle", out var obj1));
Assert.True(page.Resources.TryGetValue("Handle", out var obj2));
Assert.True(page.Resources.TryGetValue("Handle", out var obj3));
// Each access should return a NEW instance
Assert.NotSame(obj1, obj2);
Assert.NotSame(obj2, obj3);
Assert.NotSame(obj1, obj3);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment