"Items collection must be empty before using ItemsSource." "Items collection must be empty before using ItemsSource." wpf wpf

"Items collection must be empty before using ItemsSource."


I had this same error for a while in a slightly different scenario. I had

<wpftoolkit:DataGrid    AutoGenerateColumns="False"    ItemsSource="{Binding Path=Accounts}" >    <wpftoolkit:DataGridTextColumn         Header="Account Name"         Binding="{Binding Path=AccountName}" /></wpftoolkit:DataGrid>

which I fixed to be

<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>


The reason this particular exception gets thrown is that the content of the element gets applied to the ListView's Items collection. So the XAML initialises the ListView with a single local:ImageView in its Items collection. But when using an ItemsControl you must use either the Items property or the ItemsSource property, you can't use both at the same time. Hence when the ItemsSource attribute gets processed an exception is thrown.

You can find out which property the content of an element will get applied to by looking for the ContentPropertyAttribute on the class. In this case it's defined higher in the class hierarchy, on the ItemsControl:

[ContentPropertyAttribute("Items")]

The intention here was that the ListView's View be set to a local:ImageView so the fix is to explicitly indicate the property to be set.

Fix the XAML and the exception goes away:

<ListView Name="ListViewImages"          SelectionMode="Single"          ItemsSource="{Binding}">    <ListView.View>        <local:ImageView />    </ListView.View></ListView>

It was missing that <ListView.View> tag.


I just ran into a VERY insidious example of this problem. My original fragment was much more complex, which made it difficult to see the error.

   <ItemsControl                 Foreground="Black"  Background="White" Grid.IsSharedSizingScope="True"      x:Name="MyGrid" ItemsSource="{Binding}">      >      <ItemsControl.ItemsPanel>           <!-- All is fine here -->      </ItemsControl.ItemsPanel>      <ItemsControl.ItemTemplate>           <!-- All is fine here -->      </ItemsControl.ItemTemplate>      <!-- Have you caught the error yet? -->    </ItemsControl>

The bug? The extra > after the initial opening <ItemsControl> tag! The < got applied to the built-in Items collection. When the DataContext was later set, instant crashola. So look out for more than just errors surround your ItemsControl specific data children when debugging this problem.