Wpf - 相对图片源路径

15

我在我的Wpf应用程序中设置图片源时遇到了问题。 我有一个Image,其中源绑定到DataContext对象的SourceUri属性,如下所示:

<Image Source="{Binding SourceUri}"></Image>

现在,我不知道应该在我的对象的SourceUri属性上设置什么。将完整的绝对路径("c:/etc/image.jpg")设置为它会显示得很好,但显然我想要设置相对路径。我的图片存储在一个名为Resources的文件夹中,它与我的应用程序文件夹位于同一个文件夹中。最终这些图片可能来自任何地方,所以将它们添加到项目中并不是一个选项。

我已经尝试过相对于应用程序文件夹和工作路径(调试文件夹)的路径。也尝试使用“pack://..”语法,但没有成功,但是我读到这样做是没有任何意义的。

您有什么提示可以提供吗?

4个回答

18

在 System.IO.Path 中有一个方便的方法可以帮助解决这个问题:

return Path.GetFullPath("Resources/image.jpg");

这应该返回'C:\Folders\MoreFolders\Resources\image.jpg',或者在您的环境中是完整路径。它将使用当前工作文件夹作为起点。

获取GetFullPath的MSDN文档链接。


2
这很棒 - 如果我想提供自己的完整路径,它仍然可以工作。 - paddy

10

也许您可以让DataContext对象的SourceUri属性更智能一些,确定应用程序文件夹并基于此返回绝对路径。例如:

public string SourceUri
{
    get
    {
        return Path.Combine(GetApplicationFolder(), "Resources/image.jpg");
    }
}

当然可以 - 没问题 - 谢谢!目前还找不到一个好的方法来查找应用程序文件夹,所以感觉有点不正规。在 .Net 中是否有 GetApplicationFolder() 函数?我找不到这个函数。但是相对路径引用应该能够起作用吧?这些引用将相对于应用程序根文件夹,不是吗? - stiank81
1
尝试使用 Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - Mark Heath
这给了我与我正在使用的相同的结果,“Path.GetFullPath(“。”),但我猜后者取决于工作文件夹。所以我会采纳你的建议。我还有一些关于这个问题的问题,但我会解决它的。感谢您的关注! - stiank81

8
在一些令人沮丧的尝试之后,使用了


 <Image Source="pack://application:,,,/{Binding ChannelInfo/ChannelImage}">

并且

 <Image Source="pack://siteoforigin:,,,/{Binding ChannelInfo/ChannelImage}">

并且

 <Image Source="/{Binding ChannelInfo/ChannelImage}">

我通过自己实现转换器来解决这个问题:

C# 部分:

public class MyImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string path= (string)value;

        try
        {
            //ABSOLUTE
            if (path.Length > 0 && path[0] == System.IO.Path.DirectorySeparatorChar
                || path.Length > 1 && path[1] == System.IO.Path.VolumeSeparatorChar)
                return new BitmapImage(new Uri(path));

            //RELATIVE
            return new BitmapImage(new Uri(System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + path));
        }
        catch (Exception)
        {
            return new BitmapImage();
        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML方面:

<UserControl.Resources>
    <local:ImageConverter x:Key="MyImageConverter" />
    (...)
</UserControl.Resources>

<Image Source="{Binding Products/Image, Converter={StaticResource MyImageConverter}}">

干杯,

塞尔吉奥


3

Environment.CurrentDirectory会显示.exe文件所在的文件夹(除非您手动设置了.CurrentDirectory - 但是那样我们可以假设您已经知道它在哪里)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接