The actual issue here is that a change notification is being raised for each item you add.
You need to databind WrapPAnel.Children
to an INotifyCollectionChanged
instance that implements an AddRange
. The goal should be that the propery changed event is only raise once for the entire collection.
The obvious answer is, of course, just write a method which iterates
over the input collection and calls Add for each. But this really
isn’t the answer, because the question really isn’t about AddRange –
the question is really about raising a single CollectionChanged event
when adding multiple items
How do you implement this?
public void AddRange(IEnumerable<T> dataToAdd)
{
this.CheckReentrancy();
//
// We need the starting index later
//
int startingIndex = this.Count;
//
// Add the items directly to the inner collection
//
foreach (var data in dataToAdd)
{
this.Items.Add(data);
}
//
// Now raise the changed events
//
this.OnPropertyChanged("Count");
this.OnPropertyChanged("Item[]");
//
// We have to change our input of new items into an IList since that is what the
// event args require.
//
var changedItems = new List<T>(dataToAdd);
this.OnCollectionChanged(changedItems, startingIndex);
}
SOURCE: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx
But wait, you cannot bind Wrappanel
like that! You will need to use an ItemsControl
whose ItemsPanelTemplate
is set to be a WrapPanel
. See this example http://tech.pro/tutorial/830/wpf-tutorial-using-an-itemspanel
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<Image Source="Images\Aquarium.jpg" Width="100"/>
<Image Source="Images\Ascent.jpg" Width="50"/>
<Image Source="Images\Autumn.jpg" Width="200"/>
<Image Source="Images\Crystal.jpg" Width="75"/>
<Image Source="Images\DaVinci.jpg" Width="125"/>
<Image Source="Images\Follow.jpg" Width="100"/>
<Image Source="Images\Friend.jpg" Width="50"/>
<Image Source="Images\Home.jpg" Width="150"/>
<Image Source="Images\Moon flower.jpg" Width="100"/>
</ItemsControl>