在 XAML 中设置和图像 CreateOptions 和 CacheOption

问题描述 投票:0回答:2

我想像这样设置我的

CreateOptions
CacheOption

img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnDemand;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.UriSource = new Uri("C:\\Temp\\MyImage.png", UriKind.Absolute);
img.EndInit();

有没有办法在 XAML 中装饰性地执行此操作?或者我必须求助于代码隐藏吗?

wpf image xaml
2个回答
2
投票

您可以将其放入

IValueConverter
:

[ValueConversion(typeof(string), typeof(ImageSource))]
public class FilePathToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.GetType() != typeof(string) || targetType != typeof(ImageSource)) return false;
        string filePath = value as string;
        if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) return DependencyProperty.UnsetValue;
        BitmapImage image = new BitmapImage();
        try
        {
            using (FileStream stream = File.OpenRead(filePath))
            {
                image.BeginInit();
                image.StreamSource = stream;
                image.CacheOption = BitmapCacheOption.OnDemand;
                image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                image.EndInit();
            }
        }
        catch { return DependencyProperty.UnsetValue; }
        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue;
    }
}

然后您可以在 XAML 中使用它,如下所示:

<Image Source="{Binding SomeFilePath, Converter={StaticResource 
    FilePathToImageConverter}, Mode=OneWay}" />

在代码中的某处:

SomeFilePath = "C:\\Temp\\MyImage.png";

0
投票

我使用 Sheridan 提供的答案收到与丢失密钥相关的错误。更改为这个,现在对我有用

[ValueConversion(typeof(string), typeof(ImageSource))]
public class FilePathToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.GetType() != typeof(string) || targetType != typeof(ImageSource))
            return false;

        string filePath = value as string;
        if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            return DependencyProperty.UnsetValue;

        BitmapImage image = new BitmapImage();
        try
        {
            image.BeginInit();
            image.UriSource = new Uri(filePath);
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.EndInit();
        }
        catch (Exception ex)
        {
            return DependencyProperty.UnsetValue;
        }

        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.