dotnet/wpf · error · InvalidOperationException

SR.CannotUseItemsSource

Error message

SR.CannotUseItemsSource

What it means

An ItemCollection operates in one of two modes: using an ItemsSource or a direct 'internal' item list. Setting ItemsSource while the collection still holds directly-added items throws InvalidOperationException(SR.CannotUseItemsSource), because switching would discard existing content.

Solutions

  1. Clear the direct items first (Items.Clear()) before setting ItemsSource
  2. Choose one mode: either populate via ItemsSource or via Items.Add, never both
  3. Remove the direct children from XAML if a binding supplies the data

Example fix

// before
listBox.Items.Add("x");
listBox.ItemsSource = myCollection; // throws
// after
listBox.Items.Clear();
listBox.ItemsSource = myCollection;
Defensive patterns

Strategy: validation

Validate before calling

if (items.Count > 0) items.Clear();
itemsControl.ItemsSource = myCollection;

Type guard

bool safeToSetSource = items == null || items.Count == 0;

Try / catch

try { itemsControl.ItemsSource = src; } catch (InvalidOperationException ex) { itemsControl.Items.Clear(); itemsControl.ItemsSource = src; }

Prevention

When it happens

Trigger: Assigning ItemsControl.ItemsSource (which sets ItemCollection.ItemsSource) after items were added directly via Items.Add when IsUsingItemsSource is false and the internal view already has entries (RawCount > 0).

Common situations: Declaring <ItemsControl><ListBoxItem .../></ItemsControl> in XAML and also setting ItemsSource in code or via a binding; mixing data binding with hand-populated items in the same control.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/44501aaa2f57cddb. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/ItemCollection.cs:1497

        internal DependencyObject ModelParent
        {
            get { return (DependencyObject)_modelParent.Target; }
        }

        internal FrameworkElement ModelParentFE
        {
            get { return ModelParent as FrameworkElement; }
        }

        // This puts the ItemCollection into ItemsSource mode.
        internal void SetItemsSource(IEnumerable value, Func<object, object> GetSourceItem = null)
        {
            // Allow this while refresh is deferred.

            // If we're switching from Normal mode, first make sure it's legal.
            if (!IsUsingItemsSource && (_internalView != null) && (_internalView.RawCount > 0))
            {
                throw new InvalidOperationException(SR.CannotUseItemsSource);
            }

            _itemsSource = value;
            _isUsingItemsSource = true;

            SetCollectionView(CollectionViewSource.GetDefaultCollectionView(_itemsSource, ModelParent, GetSourceItem));
        }

        // This returns ItemCollection to direct mode.
        internal void ClearItemsSource()
        {
            if (IsUsingItemsSource)
            {
                // return to normal mode
                _itemsSource = null;
                _isUsingItemsSource = false;

                SetCollectionView(_internalView);   // it's ok if _internalView is null; just like uninitialized

View on GitHub (pinned to 81131a70a4)