开发者

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜