我正在尝试将控件动态添加到我的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.
有什么建议么?谢谢。