ItemsControl元素已经是另一个元素的子元素

时间:2013-05-24 10:09:11

标签: c# xaml binding windows-phone-8 itemscontrol

我正在尝试动态添加控件到ItemsControl。我正在使用RadHubTile控件,但我认为这适用于任何控件。我的XAML

<ItemsControl x:Name="itemsControl" ItemsSource="{Binding}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <telerikPrimitives:RadUniformGrid x:Name="radUniformGrid" NumberOfColumns="3" NumberOfRows="3" />       
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

添加新控件工作正常,并且正确绑定。当我离开页面并返回时,会出现问题。我收到此错误

MS.Internal.WrappedException: Element is already the child of another element. --->     System.InvalidOperationException: Element is already the child of another element.
   at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.Collection_AddValue[T](PresentationFrameworkCollection`1     collection, CValue value)
   at MS.Internal.XcpImports.Collection_AddDependencyObject[T]    (PresentationFrameworkCollection`1 collection, DependencyObject value)    
 at System.Windows.PresentationFrameworkCollection`1.AddDependencyObject(DependencyObject value)
   at System.Windows.Controls.UIElementCollection.AddInternal(UIElement value)
   at System.Windows.PresentationFrameworkCollection`1.Add(T value)
   at System.Windows.Controls.ItemsControl.AddVisualChild(Int32 index, DependencyObject container, Boolean needPrepareContainer)
   at System.Windows.Controls.ItemsControl.AddContainers()
   at System.Windows.Controls.ItemsControl.RecreateVisualChildren(IntPtr unmanagedObj)
   --- End of inner exception stack trace ---

我怀疑是因为radHubTile元素已经有了父母。也许我必须在远离页面时从visualtree或ItemsControl中删除它们?我试图通过OnBackKeyPress背后的代码来做到这一点,但我不确定如何实现这一点。或者,如果这将解决问题。

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    foreach (var item in itemsControl.Items)
    {
        UIElement uiElement =
            (UIElement)itemsControl.ItemContainerGenerator.ContainerFromItem(item);
        //this.itemsControl.Items.Remove(uiElement);      
    }            
}

修改

以上在尝试删除uiElement

时出现以下错误
{System.InvalidOperationException: Operation not supported on read-only collection.

有什么建议吗?感谢。

2 个答案:

答案 0 :(得分:0)

您似乎正在将一系列UI元素(RadHubTile)绑定到ItemsControl。您应该直接在ItemsControl集合中的XAML中将切片添加到Items,或者将切片的数据(非UI)对象绑定到ItemsSource,而不是这样做。然后使用ItemTemplate声明RadHubTile控件本身,每当创建新的ItemsControl实例时,它将作为新实例生成。

答案 1 :(得分:0)