diff --git a/src/Avalonia.Controls/Controls.cs b/src/Avalonia.Controls/Controls.cs
index 8b0e998f64..736c7e8a77 100644
--- a/src/Avalonia.Controls/Controls.cs
+++ b/src/Avalonia.Controls/Controls.cs
@@ -1,3 +1,4 @@
+using System;
using System.Collections.Generic;
using Avalonia.Collections;
@@ -13,7 +14,7 @@ namespace Avalonia.Controls
///
public Controls()
{
- ResetBehavior = ResetBehavior.Remove;
+ Configure();
}
///
@@ -21,9 +22,22 @@ namespace Avalonia.Controls
///
/// The initial items in the collection.
public Controls(IEnumerable items)
- : base(items)
+ {
+ Configure();
+ AddRange(items); // virtual member call in ctor, ok for our current implementation
+ }
+
+ private void Configure()
{
ResetBehavior = ResetBehavior.Remove;
+ Validate = item =>
+ {
+ if (item is null)
+ {
+ throw new ArgumentNullException(nameof(item),
+ $"A null control cannot be added to a {nameof(Controls)} collection.");
+ }
+ };
}
}
}
diff --git a/tests/Avalonia.Controls.UnitTests/PanelTests.cs b/tests/Avalonia.Controls.UnitTests/PanelTests.cs
index f189638c7d..a31f0dd4c2 100644
--- a/tests/Avalonia.Controls.UnitTests/PanelTests.cs
+++ b/tests/Avalonia.Controls.UnitTests/PanelTests.cs
@@ -1,3 +1,4 @@
+using System;
using System.Linq;
using Avalonia.LogicalTree;
using Avalonia.Media;
@@ -133,5 +134,12 @@ namespace Avalonia.Controls.UnitTests
renderer.Verify(x => x.AddDirty(target), Times.Once);
}
+
+ [Fact]
+ public void Adding_Null_Child_Should_Throw()
+ {
+ var panel = new Panel();
+ Assert.Throws(() => panel.Children.Add(null!));
+ }
}
}