天天看點

在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.             return (new AssemblyPart()).Load(streamInfo.Stream);
  8.         }

這個完成了從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.             XElement deploymentRoot = XDocument.Parse(appManifestString).Root;
  8.             List<XElement> deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts).ToList();
  9.             AssemblyPart assemblyPart = new AssemblyPart();
  10.             foreach (XElement xElement in deploymentParts)
  11.             {
  12.                 string source = xElement.Attribute("Source").Value;
  13.                 StreamResourceInfo streamInfo = Application.GetResourceStream(
  14.                         new StreamResourceInfo(packageStream,
  15.                         "application/binary"),
  16.                        new Uri(source, UriKind.Relative));
  17.                 assemblyPart.Load(streamInfo.Stream);
  18.             }
  19.         }

這樣先加載整個XAP檔案,然後再加載某個程式集吧,這樣就完美了。當然程式還可以再改進下,大家自己看着辦吧。

PS:多次加載沒有關系的,程式集是有HASH值的,不會有沖突或不相容的問題。

備注:未經本人授權,此文章不得轉載。---GameDevBoy

繼續閱讀