繁体   English   中英

向网格添加多个元素

[英]Add to Grid more than one element

实际上,问题是我不能在网格中添加多个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);

这是一个错误代码:指定的Visual已经是另一个Visual的子级或CompositionTarget的根。 如果添加一个空的ListBoxItem,则工作正常,但是它定义并添加自己的ListBoxItem失败。 类似于以下内容:

1)此方法只能在网格中添加一项

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

2)这样在这里工作

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

其实有什么用,请解释我错了,在此先感谢您的帮助。

视觉元素的单个实例只能添加到视觉树一次。 在您的第一个代码段中,您两次将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 ,然后在for -loop中一遍MyGrid遍地将同一项目添加到MyGrid 您可能打算写:

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

请参阅,现在在循环的每次迭代中创建一个新的ListBoxItem ,然后将其添加到MyGrid

我建议您花一些时间来学习C#实例和变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM