2016-03-03 11 views
0

我想將列表中的所有圖像設置爲網格。但我有與Children.Add在網格中添加第二個圖像的問題。 這是我的例子:網格子已經是另一個視覺或組合的根目標

List<Image> images = new List<Image>(8); 
images.AddRange(Enumerable.Repeat(new Image(), 8));//8 empty images 

然後設置圖片:

foreach (var image in images) 
{ 
    BitmapImage b = new BitmapImage(); 
    b.BeginInit(); 
    b.UriSource = new Uri("path"); 
    b.EndInit(); 
    image.Source = b; 
    image.Width = 50; 
    image.Height = 50; 
} 

然後在一個函數調用是這樣的:

private void put_images() 
{ 
    int i = 0; 
    foreach (var image in images) 
    { 
    Grid.SetRow(image, i); 
    Grid.SetColumn(image, i); 
    LayoutRoot.Children.Add(image);//here is error 
    i++; 
    } 
} 

我得到運行時錯誤:Additional information: Specified Visual is already a child of another Visual or the root of a CompositionTarget.

我不明白爲什麼,因爲我有8個不同的圖像,我不知道如何解決這個問題。

+1

是否有XAML與此相符?您是否100%肯定LayoutRoot是您期望的Grid? – WasGoodDone

+1

在添加到LayoutRoot之前,似乎有問題的圖像是作爲小孩添加的。你有沒有檢查'image.Parent'是否爲空? – Domysee

+0

我發現問題。我回答說。 –

回答

1

問題是您創建圖像的代碼。

images.AddRange(Enumerable.Repeat(new Image(), 8)); 

這是一個圖像對象,集合中有8個引用。

Enumerable.Repeat文檔說:

element
Type: TResult
The value to be repeated.

new Image()值是參考到該圖像。
這意味着您有8個對集合中同一對象的引用。

您可以通過比較列表中的第一個條目和第二個條目來輕鬆驗證。

images[0] == images[1] //=true 

溶液將是使用一個for循環來實例化的圖像。

for(int i = 0; i < 8; i++) images.Add(new Image()); 
+0

這是非常有感覺性和邏輯性的。謝謝。 –

0

看來問題在於創建圖像。 現在我不創建8個空的圖像,但我創建了圖像,然後添加到列表中。現在它的工作:

for(int i = 0; i < 8; i++) 
{ 
    Image a = new Image(); 
    BitmapImage b = new BitmapImage(); 
    b.BeginInit(); 
    b.UriSource = new Uri("path"); 
    b.EndInit(); 
    a.Source = b; 
    a.Width = 50; 
    a.Height = 50; 
    images.Add(a); 
} 
相關問題