2

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 存在某种问题。但为什么?

4

2 回答 2

2

答案是使用pack://siteoforigin:,,,/而不是pack://application:,,,/.

pack://siteoforigin适用于复制到 bin/Debug 或 bin/Release 文件夹(或其中的任何子文件夹)的任何内容文件,无论该文件是作为链接添加到项目中还是正常添加到项目中。

path://application仅适用于正常添加的内容文件(不作为链接)。

于 2009-09-16T17:24:10.167 回答
1

pack:// uri 方案仅用于资源目录内的文件,如果您只是添加文件或添加文件作为链接并将其类型设置为“内容”,它只会将文件复制到您的 bin 文件夹中,但它不会打包在应用程序资源目录中。

所以对于作为单个文件存在于目录中的文件,你不能使用pack uri方案,你必须使用正常路径的文件uri方案。如果文件作为链接添加或复制,此行为不相关,它取决于文件的导出方式。

于 2009-09-16T06:28:39.567 回答