Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/Avalonia.Controls/Design.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,40 @@ public static void SetPreviewWith(AvaloniaObject target, ITemplate<Control>? tem
s_previewWith[target] = template;
}

/// <summary>
/// Sets a preview control for the specified <see cref="AvaloniaObject"/> at design-time.
/// </summary>
/// <param name="target">The target object.</param>
/// <param name="control">The preview control.</param>
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:
// Not a supported scenario without templates; causes stack overflows.
s_previewWith[target] = null;
break;
default:
SetPreviewWith(target, new FuncTemplate<Control>(() => control));
break;
}
}

/// <summary>
/// Sets a preview template for the specified <see cref="ResourceDictionary"/> at design-time.
/// </summary>
Expand Down
12 changes: 4 additions & 8 deletions tests/Avalonia.Markup.Xaml.UnitTests/Xaml/DesignModeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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(@"
<Button xmlns='https://github.com/avaloniaui'>
<Design.PreviewWith>
<Template>
<Border>
<Button />
</Border>
</Template>
<Border />
</Design.PreviewWith>
</Button>", designMode: true);
var preview = Design.CreatePreviewWithControl(obj);
var previewBorder = Assert.IsType<Border>(preview);
Assert.IsType<Button>(previewBorder.Child);
// Should return the original control, not the preview, as this is not supported to avoid stack overflows.
Assert.Same(obj, preview);
}
}

Expand Down