Search code examples
.net-coreavaloniaui

Cannot use relative image path in Avalonia XAML


So I switched from WPF to Avalonia for my application's cross-platform usage. WPF supports relative path for image. But when I switch to Avalonia, set the Window's background to an ImageBrush with a source of a relative path of an Image (something like Images/Background.png), it outputs:

System.IO.FileNotFoundException: 'The resource Images/Background.png could not be found.'

I first thought because the string cannot be converted to IBitmap interface, but then I realised that I was wrong when I gave it the absolute path (something like C:\Users\username\source\repos\MySolution\MyProject\Images\Background.png). How can I solve this problem?

Edit: Images/Background.png is copied to output directory, and I'm using Visual Studio 2019.


Solution

  • You need to add all your assets to a tag inside your .csproj file, so that Avalonia can find them. A relative path is sufficient. If your .csproj is inside your applications' root folder, then you would need to add the following property inside your .csproj file:

    <ItemGroup>
      <AvaloniaResource Include="Images\**" />
    </ItemGroup>
    

    Recommendation

    When you create a Avalonia Project from the template inside Visual Studio, then the folder Assets will automatically be included, e.g. this will be in your .csproj by default:

    <ItemGroup>
      <AvaloniaResource Include="Assets\**" />
    </ItemGroup>
    

    I personally think it is better practice to just create an Images folder inside the Assets directory and place your images there. That way they are automatically included without you needing to modify your .csproj (assuming you used the official templates).