2013-05-01 98 views
0

當下面的代碼運行時,任何一個ImagePanel在其Control集合中都有一個控件,並且orImagePanel的Control集合爲空。我意識到,當我添加到一個集合中時,其他集合就會被清空。有誰知道爲什麼?將同一圖像對象添加到集合中會從第一個添加的集合中刪除圖像

Image imageOff = new Image(); 
imageOff.Attributes["style"] = "display:inline-Block; overflow:hidden;"; 
imageOff.ImageUrl = "/Off.png"; 

Image etherImage = imageOff; 
Image orImage = imageOff; 

orImagePanel.Controls.Add(orImage); 
eitherImagePanel.Controls.Add(etherImage); 

回答

1

因爲控件不能是兩個不同面板的子項。您需要克隆圖像對象。目前,您只是使用相同的對象引用創建2個變量。

Image etherImage = new Image(); 
etherImage .Attributes["style"] = "display:inline-Block; overflow:hidden;"; 
etherImage .ImageUrl = "/images/webdataentry/Off.png"; 

Image orImage = new Image(); // New Object! thats the key. 
orImage .Attributes["style"] = "display:inline-Block; overflow:hidden;"; 
orImage .ImageUrl = "/images/webdataentry/Off.png"; 

orImagePanel.Controls.Add(orImage); 
eitherImagePanel.Controls.Add(etherImage); 

將工作。你也可以使用Clone方法上imageOff

http://msdn.microsoft.com/de-de/library/system.drawing.image.clone.aspx

編輯:您的評論: 每個controlcontrols -Collection而只是一個單親屬性。當使用a.controls.add(b)時,也調用b.setParent(a)。由於這是一個1:n關係,將您的控件添加到另一個面板,將再次調用setParent並覆蓋第一個父項。

http://msdn.microsoft.com/de-de/library/system.windows.forms.control.parent.aspx

完全控制佈局是一個樹。每個根有許多葉子,但葉子只能有一個根。

+0

控件不能成爲多個面板的孩子的原因是什麼? – neo 2013-05-01 19:30:14

+0

你說每個控件都有一個控件集合,但爲什麼像TextBox這樣的控件會有一個控件集合?每個容器控件都有控件集合。你能指出一個關於這個父母被設置的資源嗎? – neo 2013-05-01 19:39:27

+0

@neo TextBox擴展了Control,因此它通過繼承獲取controls-collection:http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox(v=vs.95).aspx。 – dognose 2013-05-02 15:08:44

相關問題