WPF: ImageSource relative to executable location not project location

137 Views Asked by At

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
1

There are 1 best solutions below

2
On

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?