0

实际上问题是我不能在网格中添加我的 ListBoxItem 多个元素。

ListBoxItem _ListBoxItem = null;

   _ListBoxItem = LoginThread as ListBoxItem;
   LoginThread.Name = "LoginThread1";
   OkChild.Children.Insert(0, _ListBoxItem);

   _ListBoxItem = LoginThread as ListBoxItem;
   LoginThread.Name = "LoginThread2";
   OkChild.Children.Insert(1, _ListBoxItem);

这是一个获取错误代码:指定的视觉对象已经是另一个视觉对象的子对象或 CompositionTarget 的根。如果要添加一个空的ListBoxItem,那么工作正常,但它是定义和添加自己的ListBoxItem 失败。这类似于以下内容:

1) 该方法只能在 Grid 中添加一项

ListBoxItem obj = new ListBoxItem ();
obj = MyListBoxItem;

2)像这样在这里工作

ListBoxItem obj = new ListBoxItem ();
for (int i = 0; i <100 500; i + +)
MyGrid.Children.Add (obj);

实际上有什么问题,请解释我错在哪里,因为之前非常感谢您的帮助。

4

1 回答 1

0

视觉元素的单个实例只能添加到视觉树一次。在您的第一个代码段中,您要添加LoginThread两次OkChild。而不是创建一个新的ListBoxItem,你只需分配LoginThread_ListBoxItem每次。代码的正确版本如下:

ListBoxItem _ListBoxItem = null;

// Create a new ListBoxItem
_ListBoxItem = new ListBoxItem();
LoginThread.Name = "LoginThread1";
OkChild.Children.Insert(0, _ListBoxItem);

// Again, create a new ListBoxItem. We can reuse the same variable, _ListBoxItem, to refer
// to the new ListBoxItem, but it is very important that we actually create a new one.
_ListBoxItem = new ListBoxItem();
LoginThread.Name = "LoginThread2";
OkChild.Children.Insert(1, _ListBoxItem);

在您的第二个代码段中,您编写:

ListBoxItem obj = new ListBoxItem ();
obj = MyListBoxItem;

这首先创建一个新ListBoxItem的并使变量obj引用它。但是下一行然后将变量重定向obj到引用变量MyListBoxItem所引用的任何内容。您现在完全失去了对ListBoxItem您刚刚创建的任何引用。你可能是想写吗?:

ListBoxItem obj = new ListBoxItem ();
MyListBoxItem = obj;

在第三个代码段中,您创建一个ListBoxItem,然后在循环MyGrid中一遍又一遍地添加相同的项目for。你可能打算写:

for (int i = 0; i < 100; i++)
{
    ListBoxItem obj = new ListBoxItem();
    MyGrid.Child.Add(obj);
}

看,现在ListBoxItem在循环的每次迭代中都会创建一个新的,然后添加到MyGrid.

我建议您花更多时间了解C#.

于 2013-01-19T17:18:47.810 回答