指定的元素已经是另一个元素的逻辑子级。请先将其断开连接。

3

我有一个包含网格和可展开项的用户控件,问题是当我尝试打开一个使用此用户控件的新窗口时,会出现异常“指定的元素已经是另一个元素的逻辑子级。请先断开它的连接”。
这是我的代码,第一个窗口创建时运行正常,第二个窗口显示时出现异常。

 <UserControl x:Class="DiagramDesigner.WindowsUserControl"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                     xmlns:s="clr-namespace:DiagramDesigner"
                xmlns:c="clr-namespace:DiagramDesigner.Controls"
                     mc:Ignorable="d" 

                     d:DesignHeight="700" d:DesignWidth="1000">
            <UserControl.Resources>
                <ContextMenu x:Key="DesignerCanvasContextMenu">
                    <MenuItem Header="Paste" Command="{x:Static ApplicationCommands.Paste}">
                        <MenuItem.Icon>
                            <Image Source="Resources/Images/Paste.png" Width="16"/>
                        </MenuItem.Icon>
                    </MenuItem>
                    <MenuItem Header="Select All" Command="{x:Static s:DesignerCanvas.SelectAll}"/>
                </ContextMenu>
            </UserControl.Resources>

            <Grid Margin="10">
                <Grid.RowDefinitions>

                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>


                <Grid Grid.Row="1" Margin="0,10,0,0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="200"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <!-- Toolbox -->
                    <StackPanel Grid.Column="0" Margin="0,0,5,0">
                        <Expander Header="Flow Chart" Content="{StaticResource FlowChartStencils}" IsExpanded="True" />
                    </StackPanel>
                    <!-- GridSplitter -->
                    <GridSplitter Focusable="False" Width="2" Background="LightGray"
                            VerticalAlignment="Stretch" HorizontalAlignment="Right"/>
                    <!-- Designer -->
                    <GroupBox Header="Diagram" Grid.Column="1" Margin="3,0,0,0">
                        <ScrollViewer HorizontalScrollBarVisibility="Auto"
                              VerticalScrollBarVisibility="Auto">
                            <s:DesignerCanvas Focusable="true" x:Name="MyDesigner"
                                    Background="{StaticResource WindowBackgroundBrush}"
                                    Margin="10" FocusVisualStyle="{x:Null}"
                                    ContextMenu="{StaticResource DesignerCanvasContextMenu}"/>
                        </ScrollViewer>
                    </GroupBox>
                </Grid>
            </Grid>
       </UserControl>
2个回答

4

您不能将同一UIElement实例用于UI的不同部分。 要么从第一个位置中删除它并将其添加到第二个位置(不建议,但有些高级方案可以使用),要么只需创建一个新实例。 这很便宜。


1
如何将子元素从其原始父元素中移除? - eran otzap
3
ParentElement.Children.Remove(child) 的翻译是:从父元素中移除子元素。 - atomaras

1
我曾遇到这个错误,并通过反复试错找出了问题所在。
问题是什么呢?我在主/细节网格的两个上下文菜单中都使用了以下XAML代码行,使用了DevExpress的DXGrid。
<dxb:BarItemLinkSeparator />

一旦问题得到解决,我注意到堆栈跟踪实际上给出了一个小提示,指出哪个XAML元素导致了错误。堆栈跟踪的第四行以此结尾:
[snip]ILinksHolder.OnLinkAdded(BarItemLinkBase link)

BarItemLinkBaseBarItemLinkSeparator 的基类,这提示我们删除该 XAML 将解决错误。

为了提供上下文,以下是完整的堆栈跟踪:

System.InvalidOperationException: Specified element is already the logical child of another element. Disconnect it first.
  at System.Windows.FrameworkContentElement.ChangeLogicalParent(DependencyObject newParent)
  at System.Windows.FrameworkElement.AddLogicalChild(Object child)
  at DevExpress.Xpf.Bars.PopupMenu.DevExpress.Xpf.Bars.ILinksHolder.OnLinkAdded(BarItemLinkBase link)
  at DevExpress.Xpf.Bars.BarItemLinkCollection.UpdateItemLinkOnAddToCollection(BarItemLinkBase itemLink)
  at DevExpress.Xpf.Bars.BarItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
  at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CustomizablePopupMenuItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
  at System.Collections.ObjectModel.Collection`1.Add(T item)
  at DevExpress.Xpf.Bars.BarItemLinkBase.DevExpress.Xpf.Bars.IBarManagerControllerAction.Execute()
  at DevExpress.Xpf.Bars.BarManagerActionCollection.Execute()
  at DevExpress.Xpf.Bars.BarManagerActionContainer.Execute()
  at DevExpress.Xpf.Bars.BarManagerController.Execute()
  at DevExpress.Xpf.Bars.BarManagerMenuController.Execute()
  at DevExpress.Xpf.Grid.DataControlPopupMenu.ExecuteOriginationViewMenuController(Func`2 getMenuController)
  at DevExpress.Xpf.Grid.GridCellMenuInfo.ExecuteMenuController()
  at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CreateItems()
  at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.RaiseOpening()
  at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(Object value)
  at DevExpress.Xpf.Bars.PopupMenuBase.OnIsOpenCoerce(Object value)
  at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.OnIsOpenCoerce(Object value)
  at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(DependencyObject d, Object value)
  at System.Windows.DependencyObject.ProcessCoerceValue(DependencyProperty dp, PropertyMetadata metadata, EntryIndex& entryIndex, Int32& targetIndex, EffectiveValueEntry& newEntry, EffectiveValueEntry& oldEntry, Object& oldValue, Object baseValue, Object controlValue, CoerceValueCallback coerceValueCallback, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, Boolean skipBaseValueChecks)
  at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
  at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
  at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
  at System.Windows.Controls.Primitives.Popup.set_IsOpen(Boolean value)
  at DevExpress.Xpf.Bars.ContextMenuManager.ShowElementContextMenu(Object contextElement, Boolean openingFromKeyboard)
  at DevExpress.Xpf.Bars.ContextMenuManager.OpenContextMenu(Object sender, Boolean openingFromKeyboard)
  at DevExpress.Xpf.Bars.ContextMenuManager.OnContextMenuOpening(Object sender, ContextMenuEventArgs e)
  at System.Windows.Controls.ContextMenuEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
  at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
  at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
  at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
  at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
  at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
  at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
  at System.Windows.Controls.PopupControlService.RaiseContextMenuOpeningEvent(IInputElement source, Double x, Double y, Boolean userInitiated)
  at System.Windows.Controls.PopupControlService.ProcessMouseUp(Object sender, MouseButtonEventArgs e)
  at System.Windows.Controls.PopupControlService.OnPostProcessInput(Object sender, ProcessInputEventArgs e)
  at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
  at System.Windows.Input.InputManager.ProcessStagingArea()
  at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
  at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
  at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
  at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
  at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
  at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
  at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)


  System.InvalidOperationException: Specified element is already the logical child of another element. Disconnect it first.
     at System.Windows.FrameworkContentElement.ChangeLogicalParent(DependencyObject newParent)
     at System.Windows.FrameworkElement.AddLogicalChild(Object child)
     at DevExpress.Xpf.Bars.PopupMenu.DevExpress.Xpf.Bars.ILinksHolder.OnLinkAdded(BarItemLinkBase link)
     at DevExpress.Xpf.Bars.BarItemLinkCollection.UpdateItemLinkOnAddToCollection(BarItemLinkBase itemLink)
     at DevExpress.Xpf.Bars.BarItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
     at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CustomizablePopupMenuItemLinkCollection.InsertItem(Int32 index, BarItemLinkBase itemLink)
     at System.Collections.ObjectModel.Collection`1.Add(T item)
     at DevExpress.Xpf.Bars.BarItemLinkBase.DevExpress.Xpf.Bars.IBarManagerControllerAction.Execute()
     at DevExpress.Xpf.Bars.BarManagerActionCollection.Execute()
     at DevExpress.Xpf.Bars.BarManagerActionContainer.Execute()
     at DevExpress.Xpf.Bars.BarManagerController.Execute()
     at DevExpress.Xpf.Bars.BarManagerMenuController.Execute()
     at DevExpress.Xpf.Grid.DataControlPopupMenu.ExecuteOriginationViewMenuController(Func`2 getMenuController)
     at DevExpress.Xpf.Grid.GridCellMenuInfo.ExecuteMenuController()
     at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.CreateItems()
     at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.RaiseOpening()
     at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(Object value)
     at DevExpress.Xpf.Bars.PopupMenuBase.OnIsOpenCoerce(Object value)
     at DevExpress.Xpf.Bars.CustomizablePopupMenuBase.OnIsOpenCoerce(Object value)
     at DevExpress.Xpf.Bars.BarPopupBase.OnIsOpenCoerce(DependencyObject d, Object value)
     at System.Windows.DependencyObject.ProcessCoerceValue(DependencyProperty dp, PropertyMetadata metadata, EntryIndex& entryIndex, Int32& targetIndex, EffectiveValueEntry& newEntry, EffectiveValueEntry& oldEntry, Object& oldValue, Object baseValue, Object controlValue, CoerceValueCallback coerceValueCallback, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, Boolean skipBaseValueChecks)
     at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
     at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
     at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
     at System.Windows.Controls.Primitives.Popup.set_IsOpen(Boolean value)
     at DevExpress.Xpf.Bars.ContextMenuManager.ShowElementContextMenu(Object contextElement, Boolean openingFromKeyboard)
     at DevExpress.Xpf.Bars.ContextMenuManager.OpenContextMenu(Object sender, Boolean openingFromKeyboard)
     at DevExpress.Xpf.Bars.ContextMenuManager.OnContextMenuOpening(Object sender, ContextMenuEventArgs e)
     at System.Windows.Controls.ContextMenuEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
     at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
     at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
     at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
     at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
     at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
     at System.Windows.Controls.PopupControlService.RaiseContextMenuOpeningEvent(IInputElement source, Double x, Double y, Boolean userInitiated)
     at System.Windows.Controls.PopupControlService.ProcessMouseUp(Object sender, MouseButtonEventArgs e)
     at System.Windows.Controls.PopupControlService.OnPostProcessInput(Object sender, ProcessInputEventArgs e)
     at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
     at System.Windows.Input.InputManager.ProcessStagingArea()
     at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
     at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
     at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
     at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
     at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
     at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
     at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
     at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
     at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接