Указанный элемент уже является логическим дочерним элементом другого элемента. Отключи его первым "

У меня есть пользовательский элемент управления, который содержит сетку, и внутри него есть расширитель, проблема в том, что когда я пытаюсь открыть новое окно, которое использует этот пользовательский элемент управления, я получаю исключение "Указанный элемент уже является логическим дочерним элементом другого элемента. Сначала отключите его"
вот мой код и его работа, когда первые окна созданы, и исключение происходит, когда показывают второе окно

 <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 ответа

Решение

Вы не можете повторно использовать один и тот же экземпляр UIElement для разных частей пользовательского интерфейса. Либо удалите его из первого и добавьте во второй (не рекомендуется, но есть некоторые сложные сценарии, где это имеет смысл), или просто создайте новый. Это довольно дешево.

У меня была эта ошибка, и мне удалось выяснить, почему именно она произошла методом проб и ошибок.

Эта проблема? Я использовал следующую строку XAML в обоих контекстных меню для сетки основных / подробных данных, используя DXGrid от DevExpress,

<dxb:BarItemLinkSeparator />

Как только я исправил проблему, я заметил, что трассировка стека действительно дает небольшое представление о том, какой элемент XAML вызывал ошибку. Четвертая строка в трассировке стека заканчивается этим:

[snip]ILinksHolder.OnLinkAdded(BarItemLinkBase link)

BarItemLinkBase является базовым классом для BarItemLinkSeparator, что является нашей подсказкой, что удаление указанного 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)
Другие вопросы по тегам