Reputation: 1374
I have around 30 images which i want to keep as items in pivot control.But if i do all those i have encountered OutOfMemoryException. SO i was adding pivots dynamically.Now if i exceed some limit i want to remove pivot items, but if i remove on pivot selection changed i am getting InvalidException. In the snippet pivotshow is the pivot control.
void PivotShow_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AddItems();
}
private void AddItems()
{
PivotItem toadd = PivotGen(images[i]);
i = (i + 1) % (images.Length);
PivotShow.Items.Add(toadd);
try
{
if (PivotShow.Items.Count > 3)
PivotShow.Items.RemoveAt(0);
}
catch (InvalidOperationException)
{
MessageBox.Show("Operation not allowed");
}
}
private PivotItem PivotGen(string urlimage)
{
PivotItem p = new PivotItem();
p.Margin = new Thickness(0, -90, 0, 0);
Image img = new Image();
BitmapImage bmp = new BitmapImage(new Uri(urlimage, UriKind.Relative));
img.Stretch = Stretch.Fill;
img.Source = bmp;
p.Content = img;
return p;
//PivotShow.Items.Add(p);
}
thanks in advance
Upvotes: 1
Views: 1529
Reputation: 70160
This is most likely occuring because you are trying to change a collection that is currently being modified. You could defer your code as follows:
EventHandler handler = null;
handler = (s, e) =>
{
element.LayoutUpdated -= handler;
AddItems();
};
element.LayoutUpdated += handler;
The above code will invoke AddItems
on the next layout pass. Give this a go and see if it helps!
Upvotes: 1