wpf image绑定bitmap( Binding Image.Source from download memory)

本文介绍了WPF中Image控件绑定string路径及byte数组两种方式,并提供了具体的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://www.cnblogs.com/shit/archive/2011/11/10/2244816.html

首先 xaml前台image的source是用string表示的

如:<image source="1.jpg"/>

想当然地以为source="{Binding imagesource}",imagesource也是必须是string,结果闹了我一个下午。

给后来人留点脚印,想想前者探索的艰辛啊。。

首先看看这段代码

复制代码
<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 = "1.jpg" };
            img.DataContext = t;            
        }
    }

    public class Test { public string Image { set; get; } }     
}
复制代码

再来看看另一种情况,要绑定的image是下载下来的byte[],没有路径,这时候

 <Image Stretch="None" Source="{Binding imageSource}" x:Name="img"></Image>

cs:

 public class book//定义一个book类,需要绑定imagesource用ImageSource类型
    {
        public string bookname { get; set; }
        public ImageSource imagesource { get; set; }
    }

 

复制代码
 void GetFirstImageCompleted(object sender,GetFirstImageCompletedEventArgs e)
       { 
                ms = new MemoryStream(e.Result);//byte[]转stream
                BitmapImage image = new BitmapImage();
                image.SetSource(ms);
                book b = new book();
                b.imagesource =image;
                img.DataContext=b;//绑定对象
        }
复制代码

很显然,image.source绑定对象可以是ImageSource和string,事情就是这样。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值