重置使用MEF加载的控件

时间:2010-11-10 17:12:00

标签: c# silverlight-4.0 mef

我已经使用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
}

任何想法?

谢谢,

1 个答案:

答案 0 :(得分:1)

一个简单的解决方法是通过使用ExportFactory而不是Lazy来避免整个问题:创建一个新实例而不是重用旧实例。只需确保丢弃的实例得到GC而不是堆积(编辑:在ExportLifetimeContext实例中将新的实例传递给您,这会影响对象的生命周期。)

现在出现的问题听起来像是老孩子仍然认为他有父母。在你再次将他添加回容器之前(最好是在你移除他的时候),你需要告诉他他现在已经没有了。但是,UserControl.Parent是只读的。也许在父母上调用RemoveLogicalChild?我没有测试过,但是如果ExportFactory caper没有漂浮你的船那么一般大道似乎值得探索。