Silverlight Error when adding objects
I have done a couple of Silverlight experiments where I programmatically generate objects on the fly and then attempt to add them to the Canvas. In one scenario, I was trying to generate 10 circles, give them some properties and then add them to the parent object, a Canvas, in this case.
However, when I did this, I got the following runtime error: “{System.ArgumentException: Value does not fall within the expected range.” right when I try to add the instances to the parent (Children.Add()).
I wasn’t able to find out exactly why this is happening, but after
some digging, I figured that this happens because the newly created
object instances have not been given a name and therefore the runtime cannot dynamically add
two instances with the same name, or no names, for that matter…
So, to avoid this run time exception, all you have to do is to give your newly created instances a name, thus, in our case, simply add: e.SetValue(Canvas.NameProperty, <name>); to your loop…
for (int i = 0; i < 10; i++) { Ellipse e = new Ellipse(); e.SetValue(Canvas.NameProperty, "e_" + i.ToString()); e.Stroke = new SolidColorBrush(...); e.Fill = new SolidColorBrush(...); e.Width = 10; e.Height = 10; LayoutRoot.Children.Add(e); }
Not sure whether this is the cause and the fix for this issue, but it seemed to fix it…