您的位置:知识库 » .NET技术

在Silverlight中如何访问外部xap文件中UserControl

作者: TerryLee  来源: 博客园  发布时间: 2008-10-09 16:23  阅读: 6983 次  推荐: 0   原文链接   [收藏]  

 

注意它定义了一个很重要的属性Parts,通过该属性我们就可以访问所有Deployment中的程序集。好了,现在我们看如何通过AppManifest.xaml中的内容构造Deployment对象,以及遍历其中的程序集,如下代码所示:

Deployment deployment = (Deployment)XamlReader.Load(appManifestString);

Assembly assembly = null;
foreach (AssemblyPart assemblyPart in deployment.Parts)
{
    if (assemblyPart.Source == assemblyName)
    {
        String source = assemblyPart.Source;

        StreamResourceInfo streamInfo = Application.GetResourceStream(
            new StreamResourceInfo(packageStream,
            "application/binary"),
            new Uri(source,UriKind.Relative));

        assembly = assemblyPart.Load(streamInfo.Stream);
        break;
    }
}
return assembly;

注意,在遍历时如果我们找到程序集名等于我们想要访问的程序集,则直接返回该程序集。最终完整的LoadAssemblyFromXap方法代码如下:

Assembly LoadAssemblyFromXap(Stream packageStream,String assemblyName)
{
    Stream stream = Application.GetResourceStream(
            new StreamResourceInfo(packageStream, null),
            new Uri("AppManifest.xaml", UriKind.Relative)).Stream;

    String appManifestString = new StreamReader(stream).ReadToEnd();

    Deployment deployment = (Deployment)XamlReader.Load(appManifestString);

    Assembly assembly = null;
    foreach (AssemblyPart assemblyPart in deployment.Parts)
    {
        if (assemblyPart.Source == assemblyName)
        {
            String source = assemblyPart.Source;

            StreamResourceInfo streamInfo = Application.GetResourceStream(
                new StreamResourceInfo(packageStream,
                "application/binary"),
                new Uri(source,UriKind.Relative));

            assembly = assemblyPart.Load(streamInfo.Stream);
            break;
        }
    }
    return assembly;
}

得到程序集后,再使用反射创建相关的实例,并在页面上加载,如下代码所示:

Assembly assembly = LoadAssemblyFromXap(e.Result, "ExternalProject.dll");

UIElement element = assembly.CreateInstance("ExternalProject.SubPage") as UIElement;
this.holder.Children.Add(element);

运行后效果如下图所示:

TerryLee_0111 

跨域访问

在上面的示例中,不涉及到跨域(我会专门写一篇文章介绍)调用的问题,如果大家想访问的xap文件与当前xap文件不在同一站点中,需要添加跨域访问文件,如下代码所示:

clientaccesspolicy.xml:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*" />
      <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

总结

本文介绍了在Silverlight中如何访问外部xap文件这一技巧,希望对大家有所帮助。示例代码下载:

0
0

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻