简体   繁体   中英

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:

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.

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.

To elaborate on Joels answer, this is what you need to do:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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