11
votes

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?

2
you could use FrameworkElement.NameProperty instead of Canvas.NamePropertyCamilo Sanchez

2 Answers

24
votes

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!

1
votes
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);           

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

x_LayoutRoot.Children.Add(child);

you can add different NameProperty before add a child