3

i have user control that contain grid and inside it there is expander the problem is when i try to open new window that uses this user control i get an exception " Specified element is already the logical child of another element. Disconnect it first"
here is my code and its work when first windows created and the exception occur when show the second window

 <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>
Antwan
  • 3,837
  • 9
  • 41
  • 62

2 Answers2

3

You cannot reuse the same UIElement instance for different parts of the UI. Either remove it from the first and add it to the second one (not recommended but there are some advanced scenarios were it makes sense) or simply create a new one. It's pretty cheap.

atomaras
  • 2,468
  • 2
  • 19
  • 28
1

I had this error, and I managed to work out exactly why it was occurring using trial and error.

The problem? I was using the following line of XAML in both context menus for a master/detail grid, using the DXGrid from DevExpress.

<dxb:BarItemLinkSeparator />

Once I the issue was fixed, I noticed that the stack trace did actually give a small clue as to which XAML element was causing the error. The 4th line in the stack trace ends with this:

[snip]ILinksHolder.OnLinkAdded(BarItemLinkBase link)

BarItemLinkBase is the base class for BarItemLinkSeparator, which is our clue that removing said XAML will fix the error.

For context, here is the full stack trace:

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)
Contango
  • 76,540
  • 58
  • 260
  • 305