WPF Image控件的Source属性是一个ImageSource对象

1.固定的图片路径是可以的,如下:

<Image Source="../test.png" />

2.绑定的Path是一个String类型的图片路径,而实际情况它需要的是一个ImageSource,所以只需在前面标记它是一个Path类型的值就OK了!

<DataTemplate>
<Image Source="{Binding Path= IconPath}" /> </DataTemplate>

----------------------------------------------------------------------------------------------------------------------------------

很多时候,我们会使用图片来装饰UI,比如作为控件背景等。

而这些图片可以分为两种形式,即存在于本地文件系统中的图片和存在于内存中的图片

对于这两种形式的图片,在WPF中,使用方法不同,下面主要说明针对这两种形式图片的使用方法

一、存在于本地文件系统中的图片文件
对于此类图片,使用非常简单,在xaml中直接指定路径即可,如:
<Button>
<Button.Background>
<ImageBrush ImageSource="bg.jpg"/>
</Button.Background>
</Button>
对应的的C#代码为
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("bg.jpg", UriKind.Relative));
button.Background = imageBrush;
其中imageBrush.ImageSource的类型为ImageSource,而ImageSource是个抽象类,
因此我们不能直接使用它,而是使用它的子类来代替,查阅MSDN,可以看到它们的继承关系:
System.Windows.Media.ImageSource
System.Windows.Media.DrawingImage
System.Windows.Media.Imaging.BitmapSource

二、存在于内存中的图片
对于只存在于内存中的图片,用以上方法就显得无能为力了,我们应该另寻他法,下面介绍一种方法:
先看代码:

//此处图片从文件中读入用以模拟内存中的图片
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap("bg.jpg");
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
ImageBrush imageBrush = new ImageBrush();
ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
button.Background = imageBrush;
其中bitmap即是存在于内存中的Bitmap类型图片,此处使用直接加载本地图片文件模拟。
步骤是先将它保存到流中,再使用ImageSourceConverter 类的ConvertFrom方法从流中得到我们需要的图片
OK,本文到此结束,以上方法都是自己在使用中探索所得,如果有更好的方法,本人非常愿意和各位交流。

---------------------------------------------------------------------------------------------------------------------------------

<StackPanel>
<StackPanel.Resources>
<local:ImageConverter x:Key="cvt_image" />
</StackPanel.Resources>
<TextBox x:Name="txtPath" Text="E:.....aaa.jpg" />
<Image Source="{Binding ElementName=txtPath, Path=Text}"/>
<Image Source="{Binding ElementName=txtPath, Path=Text, Converter={StaticResource cvt_image}}" />
</StackPanel>

这里只是一个示范,其实是可以将数据库中取出来的二进制数据,直接转换成一个BitmapImage对象返回的:
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return new BitmapImage(new Uri(value.ToString()));
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

图片的source是ImageSource类型,而继承该类型的class有:BitmapImage (继承自BitmapSource)和DrawingImage(继承自ImageSource)。BitmapImage可以显示一个普通位图,DrawingImage可以显示矢量图

原文地址:https://www.cnblogs.com/sshh/p/4663332.html