using System; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Markup.Xaml.UnitTests.Xaml { public class ResourceDictionaryTests : XamlTestBase { [Fact] public void StaticResource_Works_In_ResourceDictionary() { using (StyledWindow()) { var xaml = @" Red "; var resources = (ResourceDictionary)AvaloniaRuntimeXamlLoader.Load(xaml); var brush = (SolidColorBrush)resources["RedBrush"]; Assert.Equal(Colors.Red, brush.Color); } } [Fact] public void DynamicResource_Finds_Resource_In_Parent_Dictionary() { var dictionaryXaml = @" "; using (StyledWindow(assets: ("test:dict.xaml", dictionaryXaml))) { var xaml = @" Red "; var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml); var windowResources = (ResourceDictionary)window.Resources; var buttonResources = (ResourceDictionary)((Button)window.Content!).Resources; Assert.True(windowResources.ContainsDeferredKey("Red")); Assert.True(buttonResources.ContainsDeferredKey("Red2")); } } [Fact] public void Item_StaticReferenced_Is_UnDeferred_On_Read() { using (StyledWindow()) { var xaml = @" "; var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml); var windowResources = (ResourceDictionary)window.Resources; var buttonResources = (ResourceDictionary)((Button)window.Content!).Resources; Assert.IsType(buttonResources["Red2"]); Assert.False(windowResources.ContainsDeferredKey("Red")); Assert.False(buttonResources.ContainsDeferredKey("Red2")); } } [Fact] public void Value_Type_With_Parse_Converter_Should_Not_Be_Deferred() { using (StyledWindow()) { var xaml = @" Red "; var resources = (ResourceDictionary)AvaloniaRuntimeXamlLoader.Load(xaml); Assert.False(resources.ContainsDeferredKey("Red")); Assert.IsType(resources["Red"]); } } [Fact] public void Value_Type_With_Ctor_Converter_Should_Not_Be_Deferred() { using (StyledWindow()) { var xaml = @" 1 1 1 1 "; var resources = (ResourceDictionary)AvaloniaRuntimeXamlLoader.Load(xaml); Assert.False(resources.ContainsDeferredKey("Margin")); Assert.IsType(resources["Margin"]); } } private IDisposable StyledWindow(params (string, string)[] assets) { var services = TestServices.StyledWindow.With( assetLoader: new MockAssetLoader(assets), theme: () => new Styles { ResourceDictionaryTests.WindowStyle(), }); return UnitTestApplication.Start(services); } private static Style WindowStyle() { return new Style(x => x.OfType()) { Setters = { new Setter( Window.TemplateProperty, new FuncControlTemplate((x, scope) => new ContentPresenter { Name = "PART_ContentPresenter", [!ContentPresenter.ContentProperty] = x[!Window.ContentProperty], }.RegisterInNameScope(scope))) } }; } } }