温故而知新:silverlight中的图片资源绑定

时间:2022-04-23
本文章向大家介绍温故而知新:silverlight中的图片资源绑定,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

先来看xaml部分

<UserControl
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Class="ListBoxSilde.UserControl1"> 
 <Grid x:Name="LayoutRoot"> 
 <Image Source="{Binding Image}" Stretch="None" x:Name="img"></Image>
 </Grid>
</UserControl>

cs部分:

using System.Windows.Controls;

namespace ListBoxSilde
{
 public partial class UserControl1 : UserControl
    {
        Test t;

 public UserControl1()
        {            
            InitializeComponent();
            t = new Test() { Image = "http://images.24city.com/jimmy/ListBoxSildeShow/img/001.jpg" };
            img.DataContext = t;            
        }
    }

 public class Test { public string Image { set; get; } }     
}

代码很简单,就是将一个类的字符串属性绑定到图片的Source

1.绝对路径

可以看到,绑定一个Url到图片是很容易的,用绝对路径即可

2.相对路径

如果不想用绝对路径,也可以采用相对路径,比如把

t = new Test() { Image = "http://images.24city.com/jimmy/ListBoxSildeShow/img/001.jpg" };

改成

t = new Test() { Image = "001.jpg" };

但是要注意的是,运行时请务必确保"001.jpg"与最终的xap文件要放在同一目录中,如果图片很多,您要是觉得放在一起很杂乱,也可以写成

t = new Test() { Image = "img/001.jpg" };

这样的前提是xap所在目录下,必须新建一个img目录,然后把001.jpg放在img目录中

3.资源引用方式

这种方式的前提是图片必须设置为资源,直接打包进xap中,引用的格式为"/程序集;component/图片的资源路径" (不知道如何将图片打包成资源的,可以参考蓝色上的这篇贴子http://bbs.blueidea.com/thread-2941697-1-1.html)

比如:/ListBoxSilde;component/img/002.jpg,如果您不清楚程序集的名称(或不想在代码里写死,也可以用反射的方法得到程序集名称),参考下面的代码:

string asmName = System.Reflection.Assembly.GetExecutingAssembly().FullName.Split(',')[0];
t = new Test() { Image = "/" + asmName + ";component/img/002.jpg" };