From a83e06067b191648065bd4a03c7fe99ce1ee1331 Mon Sep 17 00:00:00 2001 From: Julien Lebosquain Date: Mon, 13 Apr 2026 18:29:02 +0200 Subject: [PATCH 1/2] Add back Design.SetPreviewWith(AvaloniaObject, Control) overload --- src/Avalonia.Controls/Design.cs | 49 +++++++++++++++++++ .../Xaml/DesignModeTests.cs | 12 ++--- 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/Avalonia.Controls/Design.cs b/src/Avalonia.Controls/Design.cs index 1f7dd4d934b..0e7d5365733 100644 --- a/src/Avalonia.Controls/Design.cs +++ b/src/Avalonia.Controls/Design.cs @@ -15,6 +15,20 @@ public static class Design private static Dictionary?> s_previewWith = []; private static Dictionary s_templateDataContext = []; + private static ITemplate InvalidVisualTemplate + => field ??= new FuncTemplate(() => new StackPanel + { + Children = + { + new TextBlock { Text = "A Template must be specified to use Design.PreviewWith on a Visual. Example:" }, + new TextBlock { Text = "" }, + new TextBlock { Text = " " }, + new TextBlock { Text = "" } + } + }); + /// /// Gets a value indicating whether the application is running in design mode. /// @@ -142,6 +156,41 @@ public static void SetPreviewWith(AvaloniaObject target, ITemplate? tem s_previewWith[target] = template; } + /// + /// Sets a preview control for the specified at design-time. + /// + /// The target object. + /// The preview control. + public static void SetPreviewWith(AvaloniaObject target, Control? control) + { + if (control is null) + { + s_previewWith[target] = null; + return; + } + + switch (target) + { + case ResourceDictionary resourceDictionary: + SetPreviewWith(resourceDictionary, control); + break; + case IDataTemplate dataTemplate: + SetPreviewWith(dataTemplate, control); + break; + case IStyle style: + SetPreviewWith(style, control); + break; + case Visual visual: + s_previewWith[target] = null; + // TODO: restore once ITemplate overloads are correctly handled in the XAML compiler. + //SetPreviewWith(visual, InvalidVisualTemplate); + break; + default: + SetPreviewWith(target, new FuncTemplate(() => control)); + break; + } + } + /// /// Sets a preview template for the specified at design-time. /// diff --git a/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/DesignModeTests.cs b/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/DesignModeTests.cs index 42776b236c1..cb2b25f0d54 100644 --- a/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/DesignModeTests.cs +++ b/tests/Avalonia.Markup.Xaml.UnitTests/Xaml/DesignModeTests.cs @@ -33,23 +33,19 @@ public void Design_Mode_PreviewWith_Should_Be_Ignored_Without_Design_Mode() } [Fact] - public void Design_Mode_PreviewWith_Works_With_Control_Template() + public void Design_Mode_PreviewWith_Returns_Original_Control() { using (UnitTestApplication.Start(TestServices.MockWindowingPlatform)) { var obj = (Control)AvaloniaRuntimeXamlLoader.Load(@" ", designMode: true); var preview = Design.CreatePreviewWithControl(obj); - var previewBorder = Assert.IsType(preview); - Assert.IsType