【问题标题】:ItemsControl Element is already the child of another elementItemsControl 元素已经是另一个元素的子元素
【发布时间】:2013-05-19 21:51:10
【问题描述】:

我正在尝试将控件动态添加到我的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 元素已经有了父元素。离开页面时,也许我必须从可视化树或 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.

有什么建议吗?谢谢。

【问题讨论】:

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


    【解决方案1】:

    【讨论】:

    • 我收到{System.InvalidOperationException: Operation not supported on read-only collection.。 ItemsControl 项在通过绑定添加时是只读的
    • 我试过了。但我能清除的唯一方法是从网格中删除ItemsControl。然后当我返回页面时出现另一个问题,因为我必须重新添加它。我想通过 XAML 而不是后面的代码来做到这一点。
    【解决方案2】:

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

    【讨论】:

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