2014-09-25 17 views
1

我想设置我的CreateOptionsCacheOption像这样:设置和图像CreatOptions和CacheOption在XAML

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装饰品做到这一点?或者我必须诉诸代码?

回答

0

你可以把一个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 = BitmapCacheOption.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

是啊,我是害怕这一点。 – Jordan 2014-09-25 15:27:25

+0

这个解决方案有什么问题?它可以纯粹用于XAML。 – Sheridan 2014-09-25 15:29:12

+0

它没有错。我只是希望更简单一些。我的老板想让我尝试这个应用程序,我不会在100个不同的地方改变我的绑定。谢谢。 – Jordan 2014-09-25 17:02:52

相关问题