我IValueConverter
在 WPF 中有一个将相对文件路径转换为BitmapImage
.
编码:
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;
}
}
问题:
这个转换器工作得很好,直到我尝试将它与作为链接添加到项目中的文件一起使用(解决方案资源管理器 -> 添加现有项目 -> 添加为链接)。图像文件的BuildAction
设置为Content
,文件标记为Copy Always
。该文件肯定会正确复制到“bin”文件夹,但由于某种原因,转换器在到达return new BitmapImage(uri)
.
例外:
System.IO.IOException was unhandled
Message="Cannot locate resource 'images/splash.png'."
Source="PresentationFramework"
问题:
有人可以解释一下吗?这是 .NET Framework 中的错误还是预期行为?是否有解决方法或者“添加为链接”不是图像内容文件的选项?
编辑:
好的,我找到了解决方法。这是我修改后的转换器类:
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;
}
}
packuri
显然,使用带有链接文件的 a 存在某种问题。但为什么?