如何将 UIElement 添加到 List中?
我尝试将两个 Canvas
添加到 List
,但我从以下代码中收到异常:
List<Canvas> cvList = new List<Canvas>();
Canvas cv = new Canvas();
cv.Width = 100;
cv.Height = 100;
cvList.Add(cv); // adding first Canvas to List<Canvas>
cvList.Add(cv); // adding the second Canvas to List<Canvas>
...
为了详细说明该问题,每个 Canvas
code> 必须是不同的,因为每个子元素可能有不同的 TextBox
、Label 和其他 UIElement
。所以我认为上面的代码不应该工作。但是,尽管我不能这样做:
Canvas cv1 = new Canvas();
cv1.Width = 100;
Canvas cv2 = new Canvas();
cv2.Width = 250;
...
Or
Canvas[] cv = new Canvas[myInt];
我不能执行上述操作,因为列表的大小是在运行时确定的,并且我无法为数组分配大小或单独声明每个数组。
如何正确地做到这一点?是的,我已经阅读了 MSDN 上的列表,但该网站没有告诉我如何操作。谢谢。
I try to add two Canvas
to a List<Canvas>
, but I receive exception from the following code:
List<Canvas> cvList = new List<Canvas>();
Canvas cv = new Canvas();
cv.Width = 100;
cv.Height = 100;
cvList.Add(cv); // adding first Canvas to List<Canvas>
cvList.Add(cv); // adding the second Canvas to List<Canvas>
...
To elaborate more on the issue, each Canvas
has to be distinct since each may Children different TextBox
, Label and other UIElement
. So I think the above code shouldn't work. However though I cannot do this:
Canvas cv1 = new Canvas();
cv1.Width = 100;
Canvas cv2 = new Canvas();
cv2.Width = 250;
...
Or
Canvas[] cv = new Canvas[myInt];
I cannot do the above because the size of the List is determine at run time and I cannot assign a size to an Array or declare each array individually.
How to do this correctly? Yes, I've read the List on MSDN, but the site didn't tell me how to do so. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要详细说明 Joels 的答案,这就是您需要做的:
请注意,以这种方式将相同的元素两次添加到同一个
List
集合中是完全合法的,但是尝试使用相同的元素布局中两次(根据此列表的使用方式可能会发生)不是。To elaborate on Joels answer, this is what you need to do:
Note that adding the same element twice to the same
List<Canvas>
collection in this way is perfectly legal, however attempting to use the same element twice in a layout (as might happen depending on the way that this list is used) is not.您正在将相同的画布添加到列表中。如果您想要列表中有两个不同的画布,则必须制作两个画布。请注意,您可以使用相同的变量来执行此操作,只需确保在将它们添加到列表之间再次使用 new 运算符即可。
You're adding the same canvas to the list. If you want two different canvases in the list, you have to make two canvases. Note that you can do this with the same variable, just make sure you use the new operator again in between adding them to list.