I have used MEF to load in external XAPs, this works great. But when I navigate away from the page with the loaded control, then go back to it, the control is in the exact state I left it.
Now sometimes this is great, but not for the project I working on.
How do I reset the control to its initial state?
The control is loaded (successfuly) into here:
<ItemsControl x:Name="content"/>
This is in the XAML markup
I have an On NavigatedFrom Method:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
content.Items.Clear();
}
This successfuly removed the control, as before adding this, when I went back to the page it crashed telling me the control was already a child of an element.
here is the full pages code:
public partial class Wizard : IPartImportsSatisfiedNotification
{
public Wizard()
{
InitializeComponent();
CompositionInitializer.SatisfyImports(this);
var controlToLoad = IsolatedStorageHelper.GetValue("control");
if (!String.IsNullOrEmpty(controlToLoad))
{
CatalogService.AddXap(controlToLoad + ".xap");
}
else
{
NavigationService.Navigate(new Uri("/ServiceSelector", UriKind.Relative));
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
content.Items.Clear();
}
[Import]
public IDeploymentCatalogService CatalogService { get; set; }
[ImportMany(AllowRecomposition = true)]
public Lazy<UserControl>[] MefModuleList { get; set; }
#region IPartImportsSatisfiedNotification Members
public void OnImportsSatisfied()
开发者_如何学C{
MefModuleList.ToList()
.ForEach(module =>
content.Items.Add(module.Value)
);
}
#endregion
}
Anyone any ideas?
Thanks,
A simple fix would be to avoid the whole issue by using ExportFactory rather than Lazy: Create a new instance instead of reusing the old one. Just make sure the discarded instances get GC'd instead of piling up (EDIT: The new instances are handed to you in ExportLifetimeContext instances, which mange the lifespan of the object).
What's going wrong now sounds like the old child still thinks he has a parent. Before you add him back to the container again (preferably right at the point when you remove him), you need to tell him he's now parentless. UserControl.Parent is read-only, though. Maybe call RemoveLogicalChild on the parent? I haven't tested that, but the general avenue seems worth exploring, if the ExportFactory caper doesn't float your boat.
精彩评论