diff --git a/src/Avalonia.Controls/ItemsControl.cs b/src/Avalonia.Controls/ItemsControl.cs
index b797ae8295..f8aa38670f 100644
--- a/src/Avalonia.Controls/ItemsControl.cs
+++ b/src/Avalonia.Controls/ItemsControl.cs
@@ -96,7 +96,7 @@ namespace Avalonia.Controls
///
public ItemsControl()
{
- _itemsView = new(_items);
+ _itemsView = ItemsSourceView.GetOrCreate(_items);
_itemsView.PostCollectionChanged += ItemsCollectionChanged;
UpdatePseudoClasses(0);
}
diff --git a/src/Avalonia.Controls/ItemsSourceView.cs b/src/Avalonia.Controls/ItemsSourceView.cs
index 27fa7cbe48..c8fc76255c 100644
--- a/src/Avalonia.Controls/ItemsSourceView.cs
+++ b/src/Avalonia.Controls/ItemsSourceView.cs
@@ -34,7 +34,7 @@ namespace Avalonia.Controls
/// Initializes a new instance of the ItemsSourceView class for the specified data source.
///
/// The data source.
- public ItemsSourceView(IEnumerable source)
+ private protected ItemsSourceView(IEnumerable source)
{
_inner = source switch
{
@@ -166,6 +166,48 @@ namespace Avalonia.Controls
};
}
+ ///
+ /// Gets or creates an for the specified enumerable.
+ ///
+ /// The enumerable.
+ ///
+ /// This method handles the following three cases:
+ /// - If is null, returns
+ /// - If is an returns the existing
+ ///
+ /// - Otherwise creates a new
+ ///
+ public static ItemsSourceView GetOrCreate(IEnumerable? items)
+ {
+ return items switch
+ {
+ ItemsSourceView isv => isv,
+ null => ItemsSourceView.Empty,
+ _ => new ItemsSourceView(items)
+ };
+ }
+
+ ///
+ /// Gets or creates an for the specified enumerable.
+ ///
+ /// The enumerable.
+ ///
+ /// This method handles the following three cases:
+ /// - If is null, returns
+ /// - If is an returns the existing
+ ///
+ /// - Otherwise creates a new
+ ///
+ public static ItemsSourceView GetOrCreate(IEnumerable? items)
+ {
+ return items switch
+ {
+ ItemsSourceView isv => isv,
+ null => ItemsSourceView.Empty,
+ _ => new ItemsSourceView(items)
+ };
+ }
+
public IEnumerator