Silverlight 2 Beta 1 路径和文件解析

在Silverlight的论坛上经常有人讨论Silverlight是怎样解析文件路径的。这个问题也经常令人困惑。

经过实践,我得出的结论如下:

1. <Image Source="/foo.jpg" />

    前面带有斜杠的,他的根目录起源于application的目录(xap),这类文件分别设置Build Action 为Content和CopyToOutputDirectory 为Copy always,来添加文件到xap里面。如果你进入xap文件里面检查,你就会发现这些文件。

    当图片加载失败的时候,资源加载策略会回到最初的application site上,然后在xap所在的目录中寻找这个图片。值得注意的是,这里有两个site,一个是application site,一个是hosting page's site。在创建跨域的应用程序的时候,这个区别非常重要。当图片未找到的时候,会抛出一个异常。

2. <Image Source="foo.jpg" />

  使用这种引用的文件,是作为资源文件直接编译到程序集里面的。此文件的路径是和引用这个文件的xaml文件相关的。如果文件未找到,图片加载失败的事件会触发。你在xap里面找不到此文件,因为文件被编译到了程序集里面。

3.<Image Source="absolute http url" />)

这一种,就是最常见的url地址,和html的相同。

这里有个例子

<UserControl x:Class="PeteBrown.SilverlightPathTest.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="Black">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<!-- Image that is just content, with CopyToOutputDirectory -->
<Image Source="/Subfolder/image_content.jpg" Grid.Row="0" Grid.Column="0" />
<TextBlock Text="Content" Foreground="White" Grid.Row="0" Grid.Column="0" />
<!-- Image that is set as a resource, notice leading slash -->
<Image Source="Subfolder/image_resource.jpg" Grid.Row="0" Grid.Column="1" />
<TextBlock Text="Resource" Foreground="White" Grid.Row="0" Grid.Column="1" />
<!-- Absolute Url -->
<Image Source="http://www.irritatedvowel.com/pub/blog/SilverlightBalloonsforSilverlight2Beta1_B387/image.png"
Grid.Row="0" Grid.Column="2" />
<TextBlock Text="Absolute" Foreground="White" Grid.Row="0" Grid.Column="2" />
</Grid>
</UserControl>



Silverlight 2 Beta 1 路径和文件解析

Silverlight 2 Beta 1 路径和文件解析
如果你查看xap文件里面。你就会发现这样的结构

PeteBrown.SilverlightPathTest.xap

  • AppManifest.xaml
  • PeteBrown.SilverlightPathTest.dll
  • System.Windows.Controls.dll
  • System.Windows.Controls.Extended.dll
  • SubFolder
    • image_content.jpg

image_resource.jpg被编译到了PeteBrown.SilverlightPathTest.dll里面


转载于:https://www.cnblogs.com/WH9527/archive/2008/06/04/1213304.html