Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Items must be empty before using Items Source" when updating MapItemsControl.ItemsSource

I have a Map control with MapsItemControl in it:

<maps:Map x:Name="MyMap">
    <maptk:MapExtensions.Children>
        <maptk:MapItemsControl>
            <maptk:MapItemsControl.ItemTemplate>
                <DataTemplate>
                    . . .
                </DataTemplate>
            </maptk:MapItemsControl.ItemTemplate>
        </maptk:MapItemsControl>
    </maptk:MapExtensions.Children>
</maps:Map>

I populate the MapItemsControl in the code the following way:

var itemCollection = MapExtensions.GetChildren((Map)MyMap).OfType<MapItemsControl>().FirstOrDefault();
itemCollection.ItemsSource = myItemCollection;

This works correctly when adding items to the map for the first time. But if I want to update it with a new soruce item collection, I get the following error in itemCollection.ItemsSource = myItemCollection; line:

Items must be empty before using Items Source

So, I have tried by adding a line to my code, in order to remove items before setting the source again, with no success:

var itemCollection = MapExtensions.GetChildren((Map)MyMap).OfType<MapItemsControl>().FirstOrDefault();
itemCollection.Items.Clear();
itemCollection.ItemsSource = myItemCollection;

Now I get the folowing exception in line itemCollection.Items.Clear();:

Collection is in non writeable mode

How can I update the items in the MapItemsControl?

like image 708
anderZubi Avatar asked Sep 02 '13 13:09

anderZubi


1 Answers

It seems like Items gets locked if you bind it with ItemsSource... but if you add each item with Item.Add(item), it works fine. So what I ended up doing was this:

var itemCollection = MapExtensions.GetChildren((Map)MyMap)
                                  .OfType<MapItemsControl>().FirstOrDefault();
if(itemCollection != null && itemCollection.Items.Count >0)
{
    itemCollection.Items.Clear();
}
foreach(var item in YourPushpinCollection)
{
    itemCollection.Items.Add(item);
}

Hope this helps :)

like image 151
Bjørn-Vegard Thoresen Avatar answered Sep 28 '22 06:09

Bjørn-Vegard Thoresen