C# Children.Add(item) 值不在预期范围内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1214173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Children.Add(item) value does not fall within the expected range
提问by oltman
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:
我正在开发一个 Silverlight 3 应用程序,当我尝试将一个对象添加到 Canvas 时,遇到了这个非常奇怪的错误。我的代码如下:
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."
我第一次使用它时,它按预期工作。但是,当我在单击使用此代码创建的 Person 对象后点击 x_LayoutRoot.Children.Add(child) 时,我收到一个 ArgumentException,告诉我“值不在预期范围内”。
However, when I add the following code before adding child to x_LayoutRoot.Children, the problem disappears.
但是,当我在将 child 添加到 x_LayoutRoot.Children 之前添加以下代码时,问题就消失了。
child.SetValue(Canvas.NameProperty, "child" + objCount++);
Why is this happening? Is this a Silverlight bug, or (more likely) am I just missing something?
为什么会这样?这是 Silverlight 错误,还是(更有可能)我只是遗漏了什么?
采纳答案by oltman
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!
我想我已经找到了原因:我添加了多个具有相同名称的 Person 对象。因此,如果将来有人遇到此问题,请确保您的所有对象都有唯一的名称!
回答by senthil
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
您可以NameProperty
在添加孩子之前添加不同的