你可以把一个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";
是啊,我是害怕这一点。 – Jordan 2014-09-25 15:27:25
这个解决方案有什么问题?它可以纯粹用于XAML。 – Sheridan 2014-09-25 15:29:12
它没有错。我只是希望更简单一些。我的老板想让我尝试这个应用程序,我不会在100个不同的地方改变我的绑定。谢谢。 – Jordan 2014-09-25 17:02:52