温故而知新: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 { setget; } }     
}

代码很简单,就是将一个类的字符串属性绑定到图片的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" };

作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/yjmyzz/p/1619132.html