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

先来看xaml部分

ExpandedBlockStart.gif 代码
< 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部分:

ExpandedBlockStart.gif 代码
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" };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值