先来看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/图片的资源路径" 。
比如:/ListBoxSilde;component/img/002.jpg,如果您不清楚程序集的名称(或不想在代码里写死,也可以用反射的方法得到程序集名称),参考下面的代码:
string asmName = System.Reflection.Assembly.GetExecutingAssembly().FullName.Split(',')[0];
t = new Test() { Image = "/" + asmName + ";component/img/002.jpg" };
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦