13

我正在修补 Silverlight 2.0。

我有一些图像,我目前有一个用于图像源的静态 URL。有没有办法从托管控件的站点的 URL 路径动态加载图像?

或者,存储在一个地方的配置设置,它包含 URL 的基本路径,以便每个图像只包含文件名?

4

8 回答 8

16

从我收集的信息来看,您并没有尝试动态更改图像本身,而是在运行时正确确定图像的位置。

我相信简单地在图像相对 URL 前加上“../”应该可以让您到达应用程序的根目录,而不一定是站点,因为应用程序可能未托管在站点的根目录中。

如果您的 XAP 文件位于以下位置:

http://somesite.foo/app1/somethingelse/clientbin/MyFoo.xap

而你试图链接以下图像:

http://somesite.foo/app1/somethingelse/images/a/boo.png

显然,所有相对 URI 都相对于 XAP 文件所在的位置(通常是 ClientBin 文件夹),并且 Silverlight 会附加当前的 Silverlight 客户端命名空间。因此,如果您的 Silverlight 控件位于命名空间 Whoppa 中,则需要将所有图像放在 clientbin/Whoppa/ 目录中。不太方便。

解决方法是使用绝对 URI,如下所示:

新的 Uri(App.Current.Host.Source, "../images/a/boo.png");

于 2008-10-25T12:57:40.493 回答
15

在后面的代码或值转换器中,您可以执行

  Uri uri = new Uri("http://testsvr.com/hello.jpg");
  YourImage.Source = new BitmapImage(uri);
于 2008-10-24T03:38:15.977 回答
6
// create a new image
Image image = new Image();

// better to keep this in a global config singleton
string hostName = Application.Current.Host.Source.Host;                   
if (Application.Current.Host.Source.Port != 80)
    hostName += ":" + Application.Current.Host.Source.Port;

// set the image source
image.Source = new BitmapImage(new Uri("http://" + hostName + "/cute_kitten112.jpg", UriKind.Absolute));  
于 2010-10-04T08:07:37.800 回答
4

http://www.silverlightexamples.net/post/How-to-Get-Files-From-Resources-in-Silverlight-20.aspx

using System.Windows.Resources;      // StreamResourceInfo
using System.Windows.Media.Imaging;  // BitmapImage
....

StreamResourceInfo sr = Application.GetResourceStream(new Uri("SilverlightApplication1;component/MyImage.png", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.SetSource(sr.Stream);
于 2010-05-13T16:04:12.440 回答
2

SilverlightHost.Source将为您提供用于加载 XAP 文件的 URL。您可以使用它为您的图像构建一个相对 URL。

因此,例如,如果您的 XAP 托管在http://foo.bar/ClientBin/bas.xap并且您的图像存储在http://foo.bar/Images/中,您可以简单地使用 Source 获取主机名并协议来构造新的 URI。

于 2008-10-24T03:44:55.620 回答
2

img.Source = new BitmapImage(image uri) 必须有效。

于 2009-03-18T08:45:28.740 回答
2

img.Source = new BitmapImage(new Uri("/images/my-image.jpg", UriKind.Relative));将正确解析为 Silverlight 应用程序的根目录,而“../images/my-image.jpg”则不会。

这仅在动态设置图像源时的代码隐藏中是正确的。您不能在 XAML 中使用此表示法(“/”来指定根)(go fiquire,希望他们能解决这个问题)

于 2009-04-09T19:49:09.657 回答
2

仅当图像作为资源文件包含在项目中时,以下代码才对我有用:

img.Source = new BitmapImage(new Uri("/images/my-image.jpg", UriKind.Relative)); 

我无法从绝对 URL 访问 URL。甚至没有 Flickr 的图像农场 URL。

于 2009-07-15T06:25:56.453 回答