1

I want to load image from an directory under my executable location.

<ImageBrush x:Key="WindowBackground" ImageSource="./backgrounds/Zenitsu.png" Stretch="UniformToFill"/>

I have tried to use ./backgrounds/ or \backgrounds\ but both seems like finding result in project directly instead or executables's location.

My output structure is like this:

Main.exe
----backgrounds
--------Zenitsu.png
Hhry
  • 823
  • 1
  • 8
  • 19

1 Answers1

2

You could create a converter such as:

public class PathToExecutableConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter is string path)
        {
            string rootPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            return Path.Combine(rootPath, path);
        }

        return value;
    }

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

And use it as follows:

<Window.Resources>
    <local:PathToExecutableConverter x:Key="PathToExecutableConverter"></local:PathToExecutableConverter>
    <ImageBrush x:Key="WindowBackground"  ImageSource="{Binding ., Converter={StaticResource PathToExecutableConverter}, ConverterParameter=backgrounds/Zenitsu.jpg}" Stretch="UniformToFill"/>
</Window.Resources>

If the images will not change you might prefer to include them as embedded resources: How to reference image resources in XAML?

Isma
  • 14,604
  • 5
  • 37
  • 51
  • Thank you so much. Actually they are all 4k wallpapers that really affect the load speed of my application. – Hhry May 22 '21 at 12:21
  • You could look into asynchronously load the images when the application is started – Isma May 22 '21 at 12:48