图像UriSource和数据绑定

时间:2020-03-05 18:41:39  来源:igfitidea点击:

我正在尝试将自定义对象列表绑定到WPF图像,如下所示:

<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding Path=ImagePath}" />
    </Image.Source>
</Image>

但这是行不通的。这是我得到的错误:

"必须设置属性'UriSource'或者属性'StreamSource'。"

我想念什么?

解决方案

回答

我们需要实现IValueConverter接口,以将uri转换为图像。IValueConverter的Convert实现将如下所示:

BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(value as string);
image.EndInit();

return image;

然后,我们将需要在绑定中使用转换器:

<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding Path=ImagePath, Converter=...}" />
    </Image.Source>
</Image>

回答

我们也可以简单地设置Source属性,而不使用子元素。为此,类需要将图像作为位图图像返回。这是我做过的一种方式的例子

<Image Width="90" Height="90" 
       Source="{Binding Path=ImageSource}"
       Margin="0,0,0,5" />

而class属性就是这样

public object ImageSource {
    get {
        BitmapImage image = new BitmapImage();

        try {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            image.UriSource = new Uri( FullPath, UriKind.Absolute );
            image.EndInit();
        }
        catch{
            return DependencyProperty.UnsetValue;
        }

        return image;
    }
}

我想这可能比值转换器要多一些工作,但这是另一种选择。

回答

WPF具有某些类型的内置转换器。如果将Image的Source属性绑定到string或者Uri值,则WPF将使用ImageSourceConverter将该值转换为ImageSource。

所以

<Image Source="{Binding ImageSource}"/>

如果ImageSource属性是图像的有效URI的字符串表示形式,则将起作用。

我们当然可以滚动自己的Binding转换器:

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}}"/>

回答

Atul Gupta的这篇文章的示例代码涵盖了几种情况:

  • 常规资源图像绑定到XAML中的Source属性
  • 绑定资源映像,但来自代码后面
  • 通过使用Application.GetResourceStream在代码后绑定资源图像
  • 通过内存流从文件路径加载图像(从数据库加载博客图像数据时同样适用)
  • 从文件路径加载图像,但使用绑定到文件路径
  • 通过依赖属性将图像数据绑定到内部具有图像控件的用户控件
  • 与第5点相同,但还要确保文件不会被锁定在硬盘上