我正在开发一个Silverlight 4 RC应用程序,并且我正在学习使用MEF处理插件控件。我已经以相当基本的方式使它工作,但是它并不完美,我知道有更好的方法来导入多个xap文件。
基本上,在我的主机应用程序的App.xaml中,我有以下内容告诉MEF加载我的xap文件:
我确信我没有完全使用AggregateCatalog,我需要能够加载目录中的任何xap文件,而不仅仅是硬编码Uri显然不够灵活。
另外,在主机的MainPage.xaml.cs中,我有以下集合,MEF将插件放入其中:
基本上,在我的主机应用程序的App.xaml中,我有以下内容告诉MEF加载我的xap文件:
AggregateCatalog catalog = new AggregateCatalog();
DeploymentCatalog c1 = new DeploymentCatalog(new Uri("TestPlugInA.xap", UriKind.Relative));
DeploymentCatalog c2 = new DeploymentCatalog(new Uri("TestPlugInB.xap", UriKind.Relative));
catalog.Catalogs.Add(c1);
catalog.Catalogs.Add(c2);
CompositionHost.Initialize(catalog);
c1.DownloadAsync();
c2.DownloadAsync();
我确信我没有完全使用AggregateCatalog,我需要能够加载目录中的任何xap文件,而不仅仅是硬编码Uri显然不够灵活。
另外,在主机的MainPage.xaml.cs中,我有以下集合,MEF将插件放入其中:
[ImportMany(AllowRecomposition = true)]
public ObservableCollection<IPlugInApp> PlugIns { get; set; }
再次强调,这个方法可以使用,但我相信我没有正确地使用ImportMany....
最后,MainPage.xaml.cs文件实现了IPartImportsSatisfiedNotification,并且我有以下代码来处理插件加载完成的情况:
public void OnImportsSatisfied()
{
sp.Children.Clear();
foreach (IPlugInApp plugIn in PlugIns)
{
if (plugIn != null)
sp.Children.Add(plugIn.GetUserControl());
}
}
这个方法能够运行,但是它似乎有点不好看,因为它要运行n次(n是要加载的xap数量)。如果我不调用sp.Children.Clear(),当加载2个插件时,我的堆栈面板会被填充如下:
TestPlugIn A TestPlugIn A TestPlugIn B
显然我漏掉了什么。有人能指出我应该做什么吗? 谢谢!