【问题标题】:Element is already the child of another element - WinRT元素已经是另一个元素的子元素 - WinRT
【发布时间】:2015-05-11 07:41:54
【问题描述】:

我需要开发一个类似于 Windows 8 开始屏幕的结构。我有一个方法,我调用它来填充我的RecordTile。方法是这样的,

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。当我过滤瓷砖(基于搜索字符串)并将新的瓷砖列表传递给函数时,它会引发异常。

我浏览了很多帖子。他们建议从其父元素中删除元素。我每次都在清除网格的孩子。一定是哪里出了问题?

【问题讨论】:

  • 当您清除其子代时,您正在从objGrid 中删除旧的objPanel,但是您是否尝试过从旧的objPanel 中删除磁贴?

标签: c# windows-runtime windows-store-apps


【解决方案1】:

正如@Rawling 建议的那样,在objGrid.Children.Clear(); 之前清除StackPanel 的Tiles 是解决方案。在该语句之前添加了以下代码,它就像一个魅力。

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

【讨论】:

    【解决方案2】:

    错误很明显:一个 WPF/SL 控件一次只能属于 1 个父控件。也试试这个。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多