图像 UriSource 和数据绑定 [英] Image UriSource and Data Binding
问题描述
我正在尝试将自定义对象列表绑定到 WPF 图像,如下所示:
I'm trying to bind a list of custom objects to a WPF Image like this:
<Image>
<Image.Source>
<BitmapImage UriSource="{Binding Path=ImagePath}" />
</Image.Source>
</Image>
但它不起作用.这是我得到的错误:
But it doesn't work. This is the error I'm getting:
必须设置属性 'UriSource' 或属性 'StreamSource'."
我错过了什么?
推荐答案
WPF 具有针对某些类型的内置转换器.如果您将图像的 Source
属性绑定到 string
或 Uri
值,那么 WPF 在幕后将使用 ImageSourceConverter 将值转换为 图像源
.
WPF has built-in converters for certain types. If you bind the Image's Source
property to a string
or Uri
value, under the hood WPF will use an ImageSourceConverter to convert the value to an ImageSource
.
所以
<Image Source="{Binding ImageSource}"/>
如果 ImageSource 属性是图像的有效 URI 的字符串表示形式,则有效.
would work if the ImageSource property was a string representation of a valid URI to an image.
您当然可以推出自己的绑定转换器:
You can of course roll your own Binding converter:
public class ImageConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage(new Uri(value.ToString()));
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
并像这样使用它:
<Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/>
这篇关于图像 UriSource 和数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!