Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Whenever I run my code, after a specified action, I get an AgrumentException citing:
Must disconnect specified child from current parent Visual before attaching to new parent Visual.

After lot of digging, I narrowed down to the following conclusion...
C#
private void ShowChecksum(string hash) {
Checksum.Text = hash; //if I comment this line... everything is fine.
}

Where Checksum is a text block and hash is a string that is being passed by a method parameter from another thread through the Dispatcher. If I comment the above line, my code runs fine.

Any Ideas? I've been after this for a while.
And If you require some mode code, I will gladly provide it.

EDIT: Here's the declaration (only a part not all.)
XML
<StackPanel x:Name="Result" DockPanel.Dock="Top" Width="Auto" Height="Auto" HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="Collapsed" Margin="40">
                <StackPanel Orientation="Horizontal">
                    <Image x:Name="FileIcon" Source="Resources/file.png" Width="48"/>
                    <Label x:Name="FileName" VerticalAlignment="Bottom" FontSize="24"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding SelectedItem, ElementName=Algorithm}" FontSize="14" />
                    <TextBlock x:Name="Checksum" FontSize="14" />
                </StackPanel>
                <StackPanel>
                    <Button Content="Save to file" Style="{DynamicResource BlueButton}" Width="auto" Height="25" Margin="30"/>
                </StackPanel>
            </StackPanel>

Now this is kinda weird error in this situation, coz this exception is generally happens when we try to add an element to any other container.

Thanks in Advance,
Amitosh
Posted
Updated 4-May-13 3:08am
v5
Comments
stibee 4-May-13 4:47am    
Can you show the important part of View and ViewModel?
AlphaDeltaTheta 4-May-13 7:09am    
Well I'm not strictly following the MVVM pattern, that's why I haven't implemented a view model. It's under construction but is yet to me merged with the main code.
stibee 4-May-13 7:36am    
I'm not shure but maybe this will help you:
http://blog.decarufel.net/2009/03/good-practice-to-use-dispatcher-in-wpf.html
AlphaDeltaTheta 4-May-13 8:20am    
Thanks for the link. But in here I don't have an issue with the dispatcher invocation. It's something different... May be something related with how I declared the Textblock since when I attempt to change the text property, the exception is encountered. And I'm well aware of WPF's STA model.

This is a special feature of WPF: it protects the developer from the cases when some operations tries to break the hierarchy of System.Windows.Media.Visual instances based in parent-child relationship between them. "Hierarchy" means that the relationship forms a tree. Usually, the problem happens when you try to insert some instance of Visual (typically, some UIElement, such as Control in some container Visual<code> (typically, one of the derived classed of <code>System.Windows.Media.ContainerVisual), if this instance was already a child of some other instance. It could be an element of VisualCollection property of ContainerVisual or a Content.

Unfortunately, the code you presented does not show this problem, but I hope you can find end when you understand the idea. Basically, you need to understand the content model and WPF logical and visual trees (in relation to the current problem, just the visual tree). Please see:
http://msdn.microsoft.com/en-us/library/bb613548.aspx[^],
http://msdn.microsoft.com/en-us/library/ms753391.aspx[^].

This CodeProject article can also be useful: Understanding the Visual Tree and Logical Tree in WPF[^].

See also:
http://msdn.microsoft.com/en-us/library/system.windows.media.visual.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.media.containervisual.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.media.containervisual.children.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.media.visualcollection.aspx[^].

Basically, you should locate a place in your element where you insert some Visual instance is some different places as a child.

—SA
 
Share this answer
 
v2
Comments
AlphaDeltaTheta 6-May-13 7:55am    
Thanks for your explanation. But it's the part of the basics that I learnt when I started learning to code UI in WPF. In my belief I'm well aware of this and I'm absolutely not trying to break the parent-child hierarchy. I don't understand how setting a string property will break this hierarchy and neither my code introduces any new visual element into the visual tree, everything has been coded in XAML. Nor I'm breaking the STA structure of WPF. All that I'm trying to do is to SET THE VALUE OF THE "TEXT" PROPERTY OF A "TEXTBLOCK" NAMED "Checksum" to the result of my computation (A STRING) that is obtained after running a background worker and a dispatcher depending upon what the user chooses. The code to set the value is straight forward and is given in my question. In one operation it is called by another thread through a delegate using Dispatcher.BeginInvoke() and by another function which is assigned as the event handler of BackgroundWorker.RunWorkerCompleted Event. Hope you understand my problem.
Sergey Alexandrovich Kryukov 6-May-13 10:27am    
I don't understand either, but let's search a bit deeper. You have an exception, but you don't show a like where the exception is thrown, you show a line to comment out to avoid exception. This is not very informative. To start with, provide exception information. I hope, you know how to do it.
—SA
AlphaDeltaTheta 7-May-13 2:42am    
Exception is always thrown inside external code. The message is - No source available. The call stack contains only external code.
Here is the exception details as shown in the Debug Time Exception Handler Dialog:
System.ArgumentException was unhandled
HResult=-2147024809
Message=Must disconnect specified child from current parent Visual before attaching to new parent Visual.
Source=PresentationCore
StackTrace:
at System.Windows.Media.Visual.AddVisualChild(Visual child)
at System.Windows.FrameworkElement.set_TemplateChild(UIElement value)
at System.Windows.Controls.ContentPresenter.UseContentTemplate.BuildVisualTree(FrameworkElement container)
at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
at System.Windows.FrameworkElement.ApplyTemplate()
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.Border.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.Control.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.StackPanel.StackMeasureHelper(IStackMeasure measureElement, IStackMeasureScrollData scrollData, Size constraint)
at System.Windows.Controls.StackPanel.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.StackPanel.StackMeasureHelper(IStackMeasure measureElement, IStackMeasureScrollData scrollData, Size constraint)
at System.Windows.Controls.StackPanel.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.DockPanel.MeasureOverride(Size constraint)
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
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)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.Dispatc
Sergey Alexandrovich Kryukov 7-May-13 2:48am    
This is harder to debug, but possible. This may be actually not the external code. Ultimately, it can be yours but called the way you cannot see it in exception stack. The problem is the invocation of a delegate via Dispatcher. You can do two things: 1) catch all exceptions on top stack frame of all threads, and get exception information; you will get pretty much the same exception stack you have shown, but this time add Exception.InnerException information, recursively. 2) Locate the place where you do invocation using Dispatcher and put a breakpoint on the invoked delegate method. Get into it and keep debugging.
—SA
AlphaDeltaTheta 7-May-13 2:59am    
Thanks for your insights... They brought me to the right path. I solved it. I changed my framework version to 4.5 and recompiled it. It gave a more friendly exception. There was a silly misplaced binding in an unrelated component causing this error. But I didn't understand why didn't the framework v4.0 didn't report that. It remained silent until a next call to the View. .NET 4.5 generated the exception even without the call. It made me think that there is something else that's fishy and finally I traced it to the faulty binding. But at last it's solved. Headache gone!
Oh! There was a small silly error in setting the binding in another, unrelated component. The binding resolved successfully but caused problems with subsequent calls to the View for updating any component.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900