Wpf XAML中的设置和图像创建选项和缓存选项

Wpf XAML中的设置和图像创建选项和缓存选项,wpf,image,xaml,Wpf,Image,Xaml,我想设置我的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); i

我想设置我的
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中有没有一种装饰性的方法?或者我必须求助于代码隐藏吗?

您可以将其放入
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}" />

是的,我很害怕。这个解决方案怎么了?它完全可以在XAML中使用,没有任何问题。我只是希望有更简单的事情。我的老板想让我在整个应用程序中试用,我不会在100个不同的地方更改绑定。谢谢。@Sheridan将
BitmapCacheOption.IgnoreImageCache
替换为
BitmapCreateOptions.IgnoreImageCache
谢谢@Jinjinov。好的。我现在已经改正了错误。
SomeFilePath = "C:\\Temp\\MyImage.png";