0

私は Image の ListBox を持っています:

<Image Margin="0" Source="{Binding Path=ImgUrl}" HorizontalAlignment="Stretch" Width="80" Height="80" 
                                               Tag="{Binding idStr}" OpacityMask="{x:Null}" Stretch="Fill"/>

そして、バインドすると、キャッシュの問題のためにイメージがディスクに保存され、次回はイメージが存在するかどうかがチェックされ、ディスクから取得されます。このようなことは可能ですか?画像をダウンロード -> ディスクに保存 -> 画像を画像ソースとして作成

4

1 に答える 1

1

各画像をファイルに保存する専用のバインディング コンバーターを使用できます。

以下のサンプル コードは、このようなコンバータの基本構造を示しています。エラー処理を追加する必要があり、もちろん、画像 URI からローカル ファイル パスへのマッピングを定義する必要があります。System.Uri代替ソース タイプとしてサポートすることもできます。

public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var result = value;
        var imageUrl = value as string;

        if (imageUrl != null)
        {
            var buffer = (new WebClient().DownloadData(imageUrl));

            if (buffer != null)
            {
                // create an appropriate file path here
                File.WriteAllBytes("CachedImage.jpg", buffer);

                var image = new BitmapImage();
                result = image;

                using (var stream = new MemoryStream(buffer))
                {
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream;
                    image.EndInit();
                }
            }
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

次のようにバインディングでそのコンバーターを使用します。

<Image Source="{Binding Path=ImgUrl,
                Converter={StaticResource ImageConverter}}" ... />
于 2013-03-04T09:15:27.557 に答える