"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead." with no known cause

Will Pittenger 281 Reputation points
2022-04-02T06:38:01.823+00:00

I have a data bound System.Windows.Controls.ItemsControl that's giving me a mysterious runtime exception. It's acting as though I'm attempting to add items with its Items property. But I'm not. Unfortunately, the ItemsControl in question is one of a series of nested ItemsControl instances via their ItemTemplate property. The exception I'm getting doesn't specify which one. If I could tell what the DataSource value was, I might be able to figure it out. But when I look at the entries in the call stack at the point of the exception being thrown, most of the relevant values appear to be unavailable to the Debugger. I'm using Visual Studio 2022. My project is targeting .NET 6.0.

What's wrong? How do I track down which source is the problem?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,676 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,279 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
766 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Nils Berghs 1 Reputation point
    2022-09-13T14:07:03.41+00:00

    I had the exact same error message, and spent way to much time figuring it out, because of the confusing error message.

    The cause of the problem was that I defined the "dataTemplate" in an ItemsControl as content:

    <ItemsControl ItemsSource="{Binding SomeList}">  
        <Grid>  
            ... template ...  
        </Grid>  
    </ItemsControl>  
    

    Fixed it by proparly declaring the template

    <ItemsControl ItemsSource="{Binding SomeList}">  
        <ItemsControl.ItemTemplate>  
            <DataTemplate>  
                 <Grid>  
                      ... template ...  
                 </Grid>  
            </DataTemplate>  
        </ItemsControl.ItemTemplate>  
    </ItemsControl>  
    

    It something that I have already done a hundred times, but I was completely fooled by the message and started looking in the wrong file...