Wpf - 相对图像源路径

sti*_*k81 14 wpf image path

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

<Image Source="{Binding SourceUri}"></Image>
Run Code Online (Sandbox Code Playgroud)

现在,我不知道在我的对象的SourceUri属性上设置什么.设置完整的绝对路径("c:/etc/image.jpg")它显示得很好,但显然我想设置相对路径.我的图像存储在与我的应用程序文件夹位于同一文件夹中的文件夹中.最后这些图像可能来自任何地方,因此将它们添加到项目中确实不是一种选择.

我已经尝试了相对于应用程序文件夹的路径,并且相对于工作路径(debug-folder).还尝试使用"pack:// .."语法,但没有运气,但请注意,这不是任何一点.

关于我应该尝试的任何提示?

Hol*_*olf 17

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

return Path.GetFullPath("Resources/image.jpg");
Run Code Online (Sandbox Code Playgroud)

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

链接到GetFullPath上的MSDN文档.

  • 这很棒 - 如果我想提供自己的完整路径,它仍然有用. (2认同)

Mar*_*ath 10

也许你可以让你的DataContext对象的SourceUri属性更聪明,并确定应用程序文件夹是什么,并返回基于它的绝对路径.例如:

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


ser*_*iol 7

经过一段令人沮丧的时间尝试

 <Image Source="pack://application:,,,/{Binding ChannelInfo/ChannelImage}">
Run Code Online (Sandbox Code Playgroud)

 <Image Source="pack://siteoforigin:,,,/{Binding ChannelInfo/ChannelImage}">
Run Code Online (Sandbox Code Playgroud)

 <Image Source="/{Binding ChannelInfo/ChannelImage}">
Run Code Online (Sandbox Code Playgroud)

我解决了这个实现我自己的转换器:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML方面:

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

<Image Source="{Binding Products/Image, Converter={StaticResource MyImageConverter}}">
Run Code Online (Sandbox Code Playgroud)

干杯,

塞尔吉奥