解决反射加载Xap包中的图片路径问题
时间:2010-08-27 来源:吹风
图片路径问题
最近做的silverlight项目框架设计是将每个模块都做成单独的silverlight项目,这些单独项目生成的Xap包通过在父silverlight程序中
反射实现加载。在实际开发过程中,用blend添加的图片默认路径是"\123.jpg”。编译后图片会做为内容一起打包到Xap中。在图片路径中
以"\"开始的路径,silverlight运行时会从父silverlight Xap包中搜索文件,然后显示。而反射加载的xap包中的图片会找不到路径。
解决方法
解决此问题比较简单,我们需要将反射xap包中的图片设置为资源,然后将图片路径"\123.jpg”修改为"123.jpg”。
在图片路径中如果没有"\",silverlight运行时将会从资源中搜索图片。
xap包反射加载类
代码
public class XapLoader
{
public static UserControl LoadStream(Stream e, string MainPage, string MainDll)
{
string appMainfest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(e, null)
, new Uri("AppManifest.xaml", UriKind.Relative)).Stream
).ReadToEnd();
XElement xe = (XDocument.Parse(appMainfest)).Root;
var results = from deploymentPart in xe.Elements().Elements()
where deploymentPart.Attributes("Source").Count() > 0
select deploymentPart.Attribute("Source").Value;
Assembly asse = null;
foreach (var deploymentpart in results)
{
string source = deploymentpart;
StreamResourceInfo streamInfo = Application.GetResourceStream(new StreamResourceInfo(e, "application/binary"),
new Uri(source, UriKind.Relative));
AssemblyPart assP = new AssemblyPart();
if (source == MainDll)
{
asse = assP.Load(streamInfo.Stream);
}
else
{
assP.Load(streamInfo.Stream);
}
}
return asse.CreateInstance(MainPage) as UserControl;
}
public void loadUri(Uri xapuri, string MainPage, string MainDll)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler((s, e) => {
string appMainfest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(e.Result, null)
, new Uri("AppManifest.xaml", UriKind.Relative)).Stream
).ReadToEnd();
XElement xe = (XDocument.Parse(appMainfest)).Root;
var results = from deploymentPart in xe.Elements().Elements()
where deploymentPart.Attributes("Source").Count() > 0
select deploymentPart.Attribute("Source").Value;
Assembly asse = null;
foreach (var deploymentpart in results)
{
string source = deploymentpart;
StreamResourceInfo streamInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, "application/binary"),
new Uri(source, UriKind.Relative));
AssemblyPart assP = new AssemblyPart();
if (source == MainDll)
{
asse = assP.Load(streamInfo.Stream);
}
else
{
assP.Load(streamInfo.Stream);
}
}
UIElement uie = asse.CreateInstance(MainPage) as UIElement;
if (OnLoadComplete != null)
OnLoadComplete(this, new XapEventArgs() { XapRootUIElement = uie });
});
wc.OpenReadAsync(xapuri);
}
public event EventHandler<XapEventArgs> OnLoadComplete;
}
public class XapEventArgs : EventArgs
{
public UIElement XapRootUIElement { get; set; }
}
相关阅读 更多 +