简体   繁体   English

如何将UIElement添加到List <UIElement> ?

[英]How to add UIElement to List<UIElement>?

I try to add two Canvas to a List<Canvas> , but I receive exception from the following code: 我尝试将两个Canvas添加到List<Canvas> ,但是我从以下代码中收到异常:

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 . 为了详细说明这个问题,每个Canvas必须是不同的,因为每个可能会有不同的TextBox ,Label和其他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. 我无法执行上述操作,因为List的大小是在运行时确定的,我无法为数组指定大小或单独声明每个数组。

How to do this correctly? 怎么做到这一点? Yes, I've read the List on MSDN, but the site didn't tell me how to do so. 是的,我已经阅读了MSDN上的列表,但该网站没有告诉我该怎么做。 Thanks. 谢谢。

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. 请注意,您可以使用相同的变量执行此操作,只需确保在将它们添加到列表之间再次使用new运算符。

To elaborate on Joels answer, this is what you need to do: 要详细说明Joels的答案,这就是你需要做的:

List<Canvas> cvList = new List<Canvas>();

Canvas canvas1 = new Canvas();
canvas1.Width = 100; 
canvas1.Height = 100;
cvList.Add(canvas1);

Canvas canvas2 = new Canvas();
canvas2.Width = 100; 
canvas2.Height = 100;
cvList.Add(canvas2);

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. 请注意,以这种方式将相同的元素两次添加到相同的List<Canvas>集合是完全合法的,但是尝试在布局中使用相同的元素两次(可能发生取决于使用此列表的方式)不是。

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

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