我知道有可能动态地装入使用Prism或MEF框架XAP模块。但是,我不想使用这些框架;而是手动加载我的xap文件。所以,我创建了以下课程(改编自互联网):Silverlight 4中,动态加载XAP模块
public class XapLoader
{
public event XapLoadedEventHandler Completed;
private string _xapName;
public XapLoader(string xapName)
{
if (string.IsNullOrWhiteSpace(xapName))
throw new ArgumentException("Invalid module name!");
else
_xapName = xapName;
}
public void Begin()
{
Uri uri = new Uri(_xapName, UriKind.Relative);
if (uri != null)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += onXapLoadingResponse;
wc.OpenReadAsync(uri);
}
}
private void onXapLoadingResponse(object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
initXap(e.Result);
if (Completed != null)
{
XapLoadedEventArgs args = new XapLoadedEventArgs();
args.Error = e.Error;
args.Cancelled = e.Cancelled;
Completed(this, args);
}
}
private void initXap(Stream stream)
{
string appManifest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml",
UriKind.Relative)).Stream).ReadToEnd();
XElement deploy = XDocument.Parse(appManifest).Root;
List<XElement> parts = (from assemblyParts in deploy.Elements().Elements()
select assemblyParts).ToList();
foreach (XElement xe in parts)
{
string source = xe.Attribute("Source").Value;
AssemblyPart asmPart = new AssemblyPart();
StreamResourceInfo streamInfo = Application.GetResourceStream(
new StreamResourceInfo(stream, "application/binary"),
new Uri(source, UriKind.Relative));
asmPart.Load(streamInfo.Stream);
}
}
}
public delegate void XapLoadedEventHandler(object sender, XapLoadedEventArgs e);
public class XapLoadedEventArgs : EventArgs
{
public Exception Error { get; set; }
public bool Cancelled { get; set; }
}
上面的代码工作正常;我可以加载任何XAP方式如下:
XapLoader xapLoader = new XapLoader("Sales.xap");
xapLoader.Completed += new XapLoadedEventHandler(xapLoader_Completed);
xapLoader.Begin();
现在,我有一个在Sales.xap项目叫InvoiceView用户控件,所以我想将类实例。在当前项目(Main.xap)中,我添加了对Sales.xap项目的引用,但是,由于我手动加载,所以我设置了“Copy Local = False”。但是执行时,下面的代码会抛出TypeLoadException:
Sales.InvoiceView view = new Sales.InvoiceView();
看来代码找不到InvoiceView类。但是我检查了XapLoader的initXap()方法已成功执行。那么为什么代码无法找到InvoiceView类?有人可以帮我解决这个问题吗?
执行此操作的更简单方法是使用内置于Silverlight 4中的托管扩展性框架(MEF),以及.NET 4. – 2010-10-22 16:14:08