Source绑定一般式字符串,图片路径,那么如果是BMP,等得byte[]如何绑定呢??
// MainWindow.xaml
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<Image Source="{Binding ImageSource}" />
</DockPanel>
</Window>
// MainWindow.xaml.cs
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var model = new MainModel();
DataContext = model;
model.SetImageData(File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"));
}
}
class MainModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void SetImageData(byte[] data) {
var source = new BitmapImage();
source.BeginInit();
source.StreamSource = new MemoryStream(data);
source.EndInit();
// use public setter
ImageSource = source;
}
ImageSource imageSource;
public ImageSource ImageSource
{
get { return imageSource; }
set
{
imageSource = value;
OnPropertyChanged("ImageSource");
}
}
protected void OnPropertyChanged(string name)
{
var handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
起首 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,工作就是如许。
换句话说,Image可以ImageSource类,自己去实现他即可,这个类来处理字符流以及图片的加载转换关系!