Browse Source

Merge pull request #10338 from AvaloniaUI/fixes/10246-duplicate-itemscontrol-logical-children

Don't add duplicate logical children to `ItemsControl`
Max Katz 2 years ago
parent
commit
acbb412a02

+ 6 - 1
src/Avalonia.Controls/ItemsControl.cs

@@ -559,7 +559,12 @@ namespace Avalonia.Controls
             return new ItemContainerGenerator(this);
         }
 
-        internal void AddLogicalChild(Control c) => LogicalChildren.Add(c);
+        internal void AddLogicalChild(Control c)
+        {
+            if (!LogicalChildren.Contains(c))
+                LogicalChildren.Add(c);
+        }
+
         internal void RemoveLogicalChild(Control c) => LogicalChildren.Remove(c);
 
         /// <summary>

+ 19 - 0
tests/Avalonia.Controls.UnitTests/ItemsControlTests.cs

@@ -147,6 +147,25 @@ namespace Avalonia.Controls.UnitTests
             Assert.Equal(new[] { child }, target.GetLogicalChildren());
         }
 
+        [Fact]
+        public void Control_Item_Should_Be_Logical_Child_After_Layout()
+        {
+            var target = new ItemsControl
+            {
+                Template = GetTemplate(),
+            };
+            var root = new TestRoot(target);
+            var child = new Control();
+
+            target.Template = GetTemplate();
+            target.Items = new[] { child };
+            root.LayoutManager.ExecuteInitialLayoutPass();
+
+            Assert.Equal(target, child.Parent);
+            Assert.Equal(target, child.GetLogicalParent());
+            Assert.Equal(new[] { child }, target.GetLogicalChildren());
+        }
+
         [Fact]
         public void Added_Container_Should_Have_LogicalParent_Set_To_ItemsControl()
         {