我已经使用 MEF 加载外部 XAP,效果很好。 但是,当我离开带有加载控件的页面,然后返回该页面时,该控件处于我离开它时的确切状态。
现在有时这很棒,但对我从事的项目而言却不是。
如何将控件重置为初始状态?
控件已(成功)加载到此处:
<ItemsControl x:Name="content"/>
这是在 XAML 标记中
我有一个 On NavigatedFrom 方法:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
content.Items.Clear();
}
这成功地删除了控件,就像添加它之前一样,当我返回页面时它崩溃了,告诉我控件已经是一个元素的子元素。
这是完整的页面代码:
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()
{
MefModuleList.ToList()
.ForEach(module =>
content.Items.Add(module.Value)
);
}
#endregion
}
有人有什么想法吗?
谢谢,
最佳答案
一个简单的解决方法是通过使用 ExportFactory 而不是 Lazy 来避免整个问题:创建一个新实例而不是重用旧实例。只需确保丢弃的实例得到 GC 而不是堆积(编辑:新实例在 ExportLifetimeContext 实例中交给你,它管理对象的生命周期)。
现在出了什么问题,听起来老 child 仍然认为他有 parent 。在你再次把他放回容器中之前(最好是在你把他移走的时候),你需要告诉他他现在没有 parent 了。不过,UserControl.Parent 是只读的。也许在父级上调用 RemoveLogicalChild?我还没有测试过,但是如果 ExportFactory caper 没有让您满意,那么一般的途径似乎值得探索。
关于c# - 重置使用 MEF 加载的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4147056/