WPF图像UriSource、数据绑定和缓存

3

我目前已经为数据绑定的WPF图像实现了这个功能:

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

简单到足以应对。

现在,将缓存添加到这个图像中(我希望能够在加载完毕后操纵/删除本地文件)。我发现可以在 <img> 标签内添加 CacheOption="OnLoad" 来实现。

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

然后我需要一个转换器将本地文件转换为BitmapImage。
<local:LocalUriToImageConverter x:Key="myConverter2"/>

并且

public class LocalUriToImageConverter : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
        {
            return null;
        }

        if (value is string)
        {
            value = new Uri((string)value);
        }

        if (value is Uri)
        {
            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            //bi.DecodePixelWidth = 80;
            bi.DecodePixelHeight = 60;                
            bi.UriSource = (Uri)value;
            bi.EndInit();
            return bi;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}

由于某些原因,这根本没有开始工作。没有错误,但是似乎无法绑定控件。即使创建了许多实例,缩略图文件属性的get和转换器中的断点也不会被触发。切换回其他图像源标记可以正常工作。


你的输出窗口没有任何内容吗?绑定失败等情况? - Aaron McIver
一开始我遇到了很多不同的错误,尝试着让它正常工作。但最终,虽然它仍然没有真正地工作,但错误已经停止了。 - elbweb
2个回答

0

我曾经遇到过同样的问题,但是无论使用哪种转换器,都无法使绑定与BitmapImage的UriSource属性一起工作。我认为这不是它的正确使用方式。

然而,我相信以下代码是等效的,并且应该适用于您的情况(在我的情况下有效):

<Image Source="{Binding ThumbFile, Converter={StaticResource myConverter2}}" />

0
我无法从你的代码中看出发生了什么,但我会使用Snoop来深入了解并查看正在发生的事情。您应该能够看到任何绑定错误,并查看上的DataContext是什么,并确保您的DataContext上ThumbFile属性具有您期望的内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接