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: How to Create a Custom View.

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:
Exception
Items collection must be empty before using ItemsSource.
My code…
Visual Basic
Private Sub Window1_Loaded(...) Handles MyBase.Loaded ListViewImages.ItemsSource = From g In db.Graphic _ Order By g.DateAdded Ascending _ Select g End Sub
XAML
<ListView Name='ListViewImages' SelectionMode='Single' ItemsSource='{Binding}'> <local:ImageView /> </ListView>
I put a breakpoint on that line. ListViewImages.ItemsSource is Nothing just before the LINQ assignment.
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:ImageViewin itsItemscollection. But when using an ItemsControl you must use either theItemsproperty or theItemsSourceproperty, 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:
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:
It was missing that
<ListView.View>tag.