I have an IValueConverter
in WPF that converts a relative file path to a BitmapImage
.
The Code:
public class RelativeImagePathToImage : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var relativePath = (string)value;
if (string.IsNullOrEmpty(relativePath)) return Binding.DoNothing;
var path = "pack://application:,,,/" + value;
var uri = new Uri(path);
return new BitmapImage(uri);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
The Problem:
This converter was working just fine until I tried to use it with a file that was added to the project as a link (Solution Explorer -> Add Existing Item -> Add As Link). The image file's BuildAction
is set to Content
, and the file is marked Copy Always
. The file is definitely getting copied properly to the "bin" folder, but for some reason, the converter chokes when it gets to return new BitmapImage(uri)
.
The Exception:
System.IO.IOException was unhandled
Message="Cannot locate resource 'images/splash.png'."
Source="PresentationFramework"
Questions:
Can someone explain this? Is this a bug in the .NET Framework or is it expected behavior? Is there a workaround or is "Add As Link" just not an option for image content files?
Edit:
Okay, I found a workaround. Here's my revised converter class:
public class RelativeImagePathToImage : IValueConverter
{
private static string _rootPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var relativePath = (string)value;
if (string.IsNullOrEmpty(relativePath)) return Binding.DoNothing;
var path = _rootPath + "/" + relativePath;
var uri = new Uri(path);
return new BitmapImage(uri);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
Apparently, there is some kind of problem with using a packuri
with a linked file. But why?