Skip to content

Commit

Permalink
Added sanity test for logical parent.
Browse files Browse the repository at this point in the history
Allows early detection of issue #3328.
  • Loading branch information
grokys committed Dec 10, 2019
1 parent 7f11d83 commit 39fd3af
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Avalonia.Styling/StyledElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,12 @@ private static void ValidateLogicalChild(ILogical c)

private void OnAttachedToLogicalTreeCore(LogicalTreeAttachmentEventArgs e)
{
if (this.GetLogicalParent() == null && !(this is IStyleRoot))
{
throw new InvalidOperationException(
$"AttachedToLogicalTreeCore called for '{GetType().Name}' but control has no logical parent.");
}

// This method can be called when a control is already attached to the logical tree
// in the following scenario:
// - ListBox gets assigned Items containing ListBoxItem
Expand Down
23 changes: 23 additions & 0 deletions tests/Avalonia.Styling.UnitTests/StyledElementTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,29 @@ public void InheritanceParent_Should_Be_Cleared_When_Removed_From_Parent_When_Ha
Assert.Null(target.InheritanceParent);
}

[Fact]
public void Adding_Element_With_Null_Parent_To_Logical_Tree_Should_Throw()
{
var target = new Border();
var visualParent = new Panel();
var logicalParent = new Panel();
var root = new TestRoot();

// Set the logical parent...
((ISetLogicalParent)target).SetParent(logicalParent);

// ...so that when it's added to `visualParent`, the parent won't be set again.
visualParent.Children.Add(target);

// Clear the logical parent. It's now a logical child of `visualParent` but doesn't have
// a logical parent itself.
((ISetLogicalParent)target).SetParent(null);

// In this case, attaching the control to a logical tree should throw.
logicalParent.Children.Add(visualParent);
Assert.Throws<InvalidOperationException>(() => root.Child = logicalParent);
}

[Fact]
public void AttachedToLogicalParent_Should_Be_Called_When_Added_To_Tree()
{
Expand Down

0 comments on commit 39fd3af

Please sign in to comment.