Using MEF with silverlight navigation causes error - Element is already the child of another element

March 14, 2010 at 10:51 PMdsoltesz

I have recently been converting one of my silverlight apps to use MEF.  I had all my exports and imports defined and everything was working great until I tried to navigate to another page and then return to the page previous page, I would get the error, "element is already the child of another element".  So, the first thing I tried was clearing out my container controls that hosted my imported mef objects in the OnImportsSatisfied method.  I thought this would work since before I try to add any of my imported controls, I always clear out the control container first but this didn't work.  After doing some research and posting around, David Poll explained a little more detail on how SL navigation works.  What you will want to do is perform any clean up of your control containers in the OnNavigatedFrom event of your silvelright page.

protected override void OnNavigatedFrom(NavigationEventArgs e)
{

     //Perform any cleanup (ie clear out containers)

}

The reason this is necessary is that SL Navigation creates a new instance of the page every time you navigate to it (by default).  As a result, at no point were the imports cleared from the original container.  The next time you navigated to the URI, the same imports are being placed in new container instances (created when the new instance of the page was created).  This resulted in the same UI elements being given multiple parents, which is an error.

Posted in: .NET | c# | silverlight

Tags: ,

Comments (1) -

Nice post! I'm searching from google and found your blog.Thanks for sharing.

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading