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

I have a Map control with a 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 as follows:

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

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

Items must be empty before using Items Source

So, I tried adding a line to my code to remove the elements before setting the source again, without success:

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

Now I get the following exception on the line itemCollection.Items.Clear(); :

Collection is in silent mode

How to update elements in MapItemsControl ?

+6
source share
4 answers

It seems that items are locked if you bind them to ItemsSource ... but if you add each item with Item.Add (item), it works fine. So I ended up doing 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 :)

+2
source

Assuming that you continue to use the same myItemCollection to hold the current information (if you are trying to fix the source, this probably should be so), then you do not need to reinstall. Instead, you need to throw PropertyChanged events so that the component knows that you need to update the current source content. See the Sourcing Guide and the Practical Guide. Implement Microsoft property change notification for more.

0
source

Try using the DataContext property. And afaik you do not need to write Clear while using it. Just try the following:

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

Urmm .. How about

 itemCollection.Items = itemCollection.Items.Clear(); 
-1
source

Source: https://habr.com/ru/post/952980/


All Articles