using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Resources;
using System.IO;
using System.Xml.Linq;
using System.Reflection;
namespace Silverlight20.Tip
{
public partial class LoadXap : UserControl
{
public LoadXap()
{
InitializeComponent();
}
private void load_Click( object sender, RoutedEventArgs e)
{
Uri uri = new Uri( "YYTetris.xap", UriKind.Relative);
// 用 WebClient 下载指定的 XAP
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(uri);
}
void client_OpenReadCompleted( object sender, OpenReadCompletedEventArgs e)
{
/*
* StreamResourceInfo - 提供对通过 Silverlight 应用程序模型检索资源的支持
* AssemblyPart - 包含在 Silverlight 程序内的程序集
* AssemblyPart.Load() - 加载指定的程序集到当前应用程序域中
* Application.GetResourceStream() - 对 zip 类型的文件自动解压缩
*/
// YYTetris.xap 的 AppManifest.xaml 的信息如下
/*
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="YYTetris" EntryPointType="YYTetris.App" RuntimeVersion="2.0.31005.0">
<Deployment.Parts>
<AssemblyPart x:Name="YYTetris" Source="YYTetris.dll" />
</Deployment.Parts>
</Deployment>
*/
// 可以通过 Deployment.Current 检索 AppManifest.xaml 中的 Deployment 对象
// 取得 XAP 的 AppManifest.xaml 中的 Deployment.Parts 内的全部 AssemblyPart 节点信息
StreamResourceInfo resource = App.GetResourceStream(
new StreamResourceInfo(e.Result, null),
new Uri( "AppManifest.xaml", UriKind.Relative));
string resourceManifest = new StreamReader(resource.Stream).ReadToEnd();
List<XElement> assemblyParts = XDocument.Parse(resourceManifest).Root.Elements().Elements().ToList();
Assembly assembly = null;
foreach (XElement element in assemblyParts)
{
// 取出 AssemblyPart 的 Source 指定的 dll
string source = element.Attribute( "Source").Value;
AssemblyPart assemblyPart = new AssemblyPart();
StreamResourceInfo streamInfo = App.GetResourceStream(
new StreamResourceInfo(e.Result, "application/binary"),
new Uri(source, UriKind.Relative));
if (source == "YYTetris.dll")
assembly = assemblyPart.Load(streamInfo.Stream);
else
assemblyPart.Load(streamInfo.Stream);
}
// 实例化 YYTetris.xap 的主函数
var type = assembly.GetType( "YYTetris.Page");
var yyTetris = Activator.CreateInstance(type) as UIElement;
// 添加 YYTetris.xap 到指定的容器内,并更新 UI
container.Children.Add(yyTetris);
container.UpdateLayout();
}
}
}