Senger CodeLab πŸš€

Items collection must be empty before using ItemsSource

September 29, 2026

Items collection must be empty before using ItemsSource

Encountering the error message “Items collection must be empty before using ItemsSource” is a common rite of passage for many developers working with WPF (Windows Presentation Foundation) and XAML. This seemingly cryptic message often appears when you’re trying to populate a UI control like a ListBox, ComboBox, or DataGrid with data. At its core, this error signals a fundamental misunderstanding or misapplication of how WPF handles data binding. It&39;s a crucial alert that you&39;re attempting to use two mutually exclusive mechanisms for populating a control, leading to a conflict in its internal data management. Understanding the root cause is the first step toward building robust and maintainable WPF applications, especially when dealing with dynamic data.

Infographic here: Visual representation of Items vs. ItemsSource
Understanding the Conflict: Items vs. ItemsSource -------------------------------------------------

The core of the “Items collection must be empty before using ItemsSource” error lies in the dual nature of how WPF controls can display collections of data. Many WPF ItemsControl derivatives, such as ListBox, ComboBox, and DataGrid, offer two primary ways to populate their content: directly adding items to the Items property or binding a data source to the ItemsSource property. These two approaches, while serving the same end goal of displaying data, are fundamentally incompatible and designed for different scenarios.

The Items property is a direct collection, often an ItemCollection, that allows you to manually add individual UI elements or data objects. This approach is straightforward for static content or when you need fine-grained control over each item’s presentation without using data templates. For example, you might add a few ListBoxItem objects directly in XAML or programmatically in code-behind. However, this method quickly becomes cumbersome and inefficient for dynamic data that changes frequently or comes from a backend service.

Conversely, the ItemsSource property is the cornerstone of data binding in WPF. When you set ItemsSource to a collection of objects (like a List, Array, or preferably an ObservableCollection), the control automatically generates UI elements for each item in that collection. This paradigm is incredibly powerful, enabling the separation of concerns (MVVM pattern), automatic UI updates when the underlying data changes, and efficient handling of large datasets. The ItemsControl takes care of creating, recycling, and destroying UI elements based on the bound collection, often utilizing DataTemplates for custom visual representation.

The conflict arises because an ItemsControl cannot simultaneously manage items added directly to its Items collection and items supplied via its ItemsSource property. It needs a single source of truth for its content. If you manually add even one item to the Items collection, and then attempt to set the ItemsSource, the control will throw the “Items collection must be empty before using ItemsSource” error, indicating that its direct item management mechanism is already engaged.

Common Scenarios Leading to the Error

This error typically surfaces when developers inadvertently mix direct item population with data binding. A common scenario involves initial attempts to populate a control in XAML, followed by a programmatic attempt to bind data. For instance, a developer might define a ListBox in XAML and add a few tags directly, then later in the code-behind, try to set its ItemsSource to an ObservableCollection. This immediate conflict prevents the ItemsSource from taking over.

Another frequent cause is the misunderstanding of how ItemsControl derivatives like ComboBox or DataGrid work. Developers might try to add items to a ComboBox using myComboBox.Items.Add(newItem) while simultaneously trying to set myComboBox.ItemsSource = myCollection. This dual approach will inevitably trigger the error. The control is designed to manage its children either directly through the Items property (for static, pre-defined content) or indirectly through ItemsSource (for dynamic, data-bound content), but never both at the same time.

Consider a ListBox intended to display a list of users. If you initially define it in XAML like this:

 <ListBox> <ListBoxItem>John Doe</ListBoxItem> </ListBox> 

Then, in your C code, you try to bind an ObservableCollection of user objects: ``` public ObservableCollection Users { get; set; } = new ObservableCollection(); // … later myListBox.ItemsSource = Users;


 The XAML-defined ListBoxItem already populates the Items collection, preventing ItemsSource from being set. This is a classic demonstration of the error in action. Always remember that for data binding, the Items collection must be empty before using ItemsSource.  Even if you don't explicitly add ListBoxItem elements in XAML, sometimes implicit item additions can occur. For example, if you place arbitrary content directly inside an ItemsControl that isn't a DataTemplate, it might be interpreted as a direct item. Always ensure that when you intend to use ItemsSource, the Items collection remains untouched. For more details on WPF data binding, you can refer to the [Microsoft Docs on Data Binding Overview](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/data-binding-overview?view=netdesktop-6.0).

Resolving the Conflict: Best Practices for Data Binding
-------------------------------------------------------

 The most effective way to resolve the "Items collection must be empty before using ItemsSource" error and prevent it from recurring is to fully embrace the data binding paradigm in WPF. This involves consistently using the ItemsSource property for populating controls with dynamic data and avoiding direct manipulation of the Items collection when ItemsSource is intended.

### Prioritize ItemsSource with ObservableCollection

 For dynamic data that needs to reflect changes in the UI (e.g., adding, removing, or updating items), always use ItemsSource bound to an ObservableCollection<t>. This collection type automatically notifies the UI when its contents change, making it ideal for responsive applications. </t>

1. **Declare your collection:** In your ViewModel or code-behind, declare a public property of type ObservableCollection<t> where T is your data model. ```
     public ObservableCollection<MyDataItem> MyDataItems { get; set; } = new ObservableCollection<MyDataItem>(); 
    ```
    
     </t>
2. **Populate the collection:** Add your data objects to this ObservableCollection. ```
     MyDataItems.Add(new MyDataItem { Name = "Item 1", Value = 10 }); MyDataItems.Add(new MyDataItem { Name = "Item 2", Value
    <b>Question & Answer : </b><br></br><p>I'm trying to get images to display in a WPF ListView styled like a WrapPanel as described in this old ATC Avalon Team article: <a href="http://blogs.msdn.com/atc_avalon_team/archive/2006/04/28/585844.aspx" rel="noreferrer">How to Create a Custom View</a>.</p> <p><img height="200" src="https://i.sstatic.net/IFIg5.png" width="300"></img></p> <p>When I try to populate the ListView with a LINQ-to-Entities queried collection of ADO.NET Entity Framework objects I get the following exception:</p> <p><strong>Exception</strong></p> <blockquote> <p>Items collection must be empty before using ItemsSource.</p> </blockquote> <p>My code…</p> <p><strong>Visual Basic</strong></p> Private Sub Window1_Loaded(...) Handles MyBase.Loaded ListViewImages.ItemsSource = From g In db.Graphic _ Order By g.DateAdded Ascending _ Select g End Sub  <p><strong>XAML</strong></p> <ListView Name="ListViewImages" SelectionMode="Single" ItemsSource="{Binding}"> <local:ImageView /> </ListView>  <p>I put a breakpoint on that line. ListViewImages.ItemsSource is Nothing just before the LINQ assignment.</p>
    <br></br><p>I had this same error for a while in a slightly different scenario. The cause was invalid XAML, because some tags were missing.</p> <p>I had</p> <wpftoolkit:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Accounts}" > <wpftoolkit:DataGridTextColumn Header="Account Name" Binding="{Binding Path=AccountName}" /> </wpftoolkit:DataGrid>  <p>which I fixed to be</p> <wpftoolkit:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Accounts}" > <wpftoolkit:DataGrid.Columns> <wpftoolkit:DataGridTextColumn Header="Account Name" Binding="{Binding Path=AccountName}" /> </wpftoolkit:DataGrid.Columns> </wpftoolkit:DataGrid> 
    ```