Wpf - relative image source path

后端 未结 4 570
轮回少年
轮回少年 2020-12-01 16:27

I\'m having problems setting the source for images in my Wpf application. I have an Image where the source is bound to the SourceUri property of the DataContext object, like

相关标签:
4条回答
  • 2020-12-01 17:07

    Perhaps you could make the SourceUri property of your DataContext object a bit cleverer, and determine what the application folder is, and return an absolute path based on that. For example:

    public string SourceUri
    {
        get
        {
            return Path.Combine(GetApplicationFolder(), "Resources/image.jpg");
        }
    }
    
    0 讨论(0)
  • 2020-12-01 17:15

    There's a handy method in System.IO.Path which can help with this:

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

    This should return 'C:\Folders\MoreFolders\Resources\image.jpg' or whatever the full path is in your context. It will use the current working folder as the starting point.

    Link to MSDN documentation on GetFullPath.

    0 讨论(0)
  • 2020-12-01 17:26

    After some frustrating times trying with

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

    and

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

    and

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

    I solved this implementing my own converter:

    C# side:

    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 side:

    <UserControl.Resources>
        <local:ImageConverter x:Key="MyImageConverter" />
        (...)
    </UserControl.Resources>
    
    <Image Source="{Binding Products/Image, Converter={StaticResource MyImageConverter}}">
    

    Cheers,

    Sérgio

    0 讨论(0)
  • 2020-12-01 17:26

    Environment.CurrentDirectory will show you the folder the .exe is stored in (that is unless you manually set a .CurrentDirectory - but then we can assume you already know where it is).

    0 讨论(0)
提交回复
热议问题