views:

831

answers:

1

I'm developing a Silverlight 3 App and getting this really weird error when I try to add an object to a Canvas. My code is as follows:

for (int i = 0; i < person.Children.Count; i++)
        {
            //Add children in same position as parent
            Person child = person.Children[i];
            child.x_PositionTransform.X = person.x_PositionTransform.X;
            child.x_PositionTransform.Y = person.x_PositionTransform.Y;
            child.Click += new RoutedEventHandler(person_Click);
            x_LayoutRoot.Children.Add(child);
        }

The first time I use this, it works as expected. However, when I hit x_LayoutRoot.Children.Add(child) after clicking a Person object that was created using this code, I get an ArgumentException telling me that "Value does not fall within the expected range."

However, when I add the following code before adding child to x_LayoutRoot.Children, the problem disappears.

child.SetValue(Canvas.NameProperty, "child" + objCount++);

Why is this happening? Is this a Silverlight bug, or (more likely) am I just missing something?

+3  A: 

I think I've figured out the cause of this: I was adding multiple Person objects with the same name. So, if anyone has this issue in the future, make sure all of your objects have unique names!

oltman
Had the same issue several times and I am now putting as the most probable cause to NullReferenceExceptions on a `...Children.Add(obj)` call.
WmasterJ