2015-05-11 76 views
0

我需要開發一個類似於Windows 8 Start結構的結構。我有一個方法,我打電話來填充我的RecordTile。方法是,元素已經是另一個元素的孩子 - WinRT

public static void fnShowTiles(List<RecordTile> objList, Grid objGrid) // objGrid is root Grid which holds this structure 
    { 
     try 
     { 
      // copy the list into local variable 
      List<RecordTile> objListOfTiles = objList.ToList<RecordTile>(); 

      int nColumnsCount = -1; 
      objGrid.Children.Clear(); 
      objGrid.ColumnDefinitions.Clear(); 
      StackPanel objPanel = new StackPanel(); 

      int nOriginalListCount = objListOfTiles.Count; 
      int nRowsToRender = 4; 

      while (objListOfTiles.Count > 0) 
      { 
       // add new column to the grid 
       objGrid.ColumnDefinitions.Add(new ColumnDefinition()); 
       nColumnsCount += 1; 

       // add new stackpanel to newly added column 
       objPanel = new StackPanel(); 

       objGrid.Children.Add(objPanel); 
       Grid.SetColumn(objPanel, nColumnsCount); 

       // add elements to stackpanel 
       int i = 0; 
       while (i < nRowsToRender) 
       { 
        if (objListOfTiles.Count > 0) 
        { 
         // add first element and remove it from list, so that next element will be first 
         RecordTile tile = objListOfTiles.First(); 
         objPanel.Children.Add(tile); // exception occurs here 
         objListOfTiles.Remove(tile); 
         i++; 
        } 
        else 
        { 
         // if while adding elements, list finishes, then break the loop 
         break; 
        } 
       } 
      } 
    } 

這對第一次加載工作正常。我有一個SearchBox在這些瓷磚正在加載的同一頁上。當我過濾瓷磚(基於搜索字符串)並將新的瓷磚列表傳遞給函數時,它會拋出異常。

我經歷了很多帖子。他們建議從其父母移除元素。我每次都清理電網的孩子。什麼一定是出問題了?

+1

當您清除它的子項時,您正在從'objGrid'中刪除舊的'objPanel',但是您嘗試從舊的'objPanel'中刪除瓷磚嗎? – Rawling

回答

0

由於@Rawling建議,在objGrid.Children.Clear();之前清除Tiles StackPanel是解決方案。在該陳述之前添加了以下代碼,並且它像魅力一樣工作。

foreach (StackPanel panel in objGrid.Children) 
{ 
    panel.Children.Clear(); 
} 
0

錯誤很明顯:WPF/SL控件一次只能屬於1個父控件。試試這個。

protected override void OnNavigatedFrom(NavigationEventArgs e) 
    { 
      base.OnNavigatedFrom(e); 
     foreach (StackPanel panel in objGrid.Children) 
      { 
       panel.Children.Clear(); 
      } 
    } 
相關問題