在Silverlight中加载外部XAP中的控件

不多说了,网上虽然有许多代码,但是是在Silverlight 2 RC0以前的版本才能用,现在Silverlight到了2.0正式版了,代码必须变一变了。不过国内好像关注的人不多,一点相关的资料都没有。下面是代码。

  1. public static Assembly LoadAssemblyFromXap(Stream packageStream, String assemblyName)
  2.         {
  3.             StreamResourceInfo streamInfo = Application.GetResourceStream(
  4.                       new StreamResourceInfo(packageStream,
  5.                       "application/binary"),
  6.                       new Uri(assemblyName, UriKind.Relative));
  7.             
  8.             return (new AssemblyPart()).Load(streamInfo.Stream);
  9.         }

 

这个完成了从XAP中加载某个程序集。但是有个问题,一个XAP文件中可能包含多个程序集(多个DLL),那么就是需要加载整个XAP文件。不多说,还是上代码。

  1. public static void LoadXap(Stream packageStream)
  2.         {
  3.             Stream stream = Application.GetResourceStream(
  4.             new StreamResourceInfo(packageStream, null),
  5.             new Uri("AppManifest.xaml", UriKind.Relative)).Stream;
  6.             String appManifestString = new StreamReader(stream).ReadToEnd();
  7.             
  8.             XElement deploymentRoot = XDocument.Parse(appManifestString).Root;
  9.             List<XElement> deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts).ToList();
  10.             AssemblyPart assemblyPart = new AssemblyPart();
  11.             foreach (XElement xElement in deploymentParts)
  12.             {
  13.                 string source = xElement.Attribute("Source").Value;
  14.                 StreamResourceInfo streamInfo = Application.GetResourceStream(
  15.                         new StreamResourceInfo(packageStream,
  16.                         "application/binary"),
  17.                        new Uri(source, UriKind.Relative));
  18.                 assemblyPart.Load(streamInfo.Stream);
  19.             }
  20.         }

这样先加载整个XAP文件,然后再加载某个程序集吧,这样就完美了。当然程序还可以再改进下,大家自己看着办吧。

PS:多次加载没有关系的,程序集是有HASH值的,不会有冲突或不兼容的问题。

 

 

备注:未经本人授权,此文章不得转载。---GameDevBoy

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值