Many applications need to include assets such as bitmaps and resource dictionaries within their executable and refer to these assets from XAML.
Assets can be included in an application by using the
<AvaloniaResource> item in your project file. The MVVM Application template by default includes all files in the
Assets directory as an
You can include whatever files you want by adding additional
You will notice that we're referring to assets here whereas the MSBuild item is called an Avalonia resource. Assets are internally stored as .NET resources but because the term "resource" conflicts with XAML resources we'll refer to them as "assets" throughout.
Assets can be referenced in XAML by specifying their relative path:
Or their rooted path:
If the asset is located in a different assembly from the XAML file, then use the
avares: URI scheme. For example, if the asset is contained in an assembly called
MyAssembly.dll, then you would use:
In case of fonts, you can provide a font name after a '#' sign:
Avalonia provides converters which can load assets for bitmaps, icons and fonts out of the box. So an assets Uri can be automatically converted to any of following types: IImage, IBitmap, WindowIcon and FontFamily
Referencing manifest resources
Assets can also be included in .NET applications by using the
<EmbeddedResource> MSBuild item which causes the file to be included in the assembly as a manifest resource.
You can reference manifest resources using the
resm: URL scheme:
Or if the resource is embedded in a different assembly to the XAML file:
The name of the asset is automatically generated by MSBuild from the assembly name, the file path and the filename - all separated with periods. If Avalonia is unable to find a manifest resource, check the resource name using
Note: starting with 11.0 Avalonia doesn't support manifest "resm" resources anymore. Use Avalonia Resources instead (avares).
Loading assets from code
Assets can be loaded from code using the
var assets = AvaloniaLocator.Current.GetService<IAssetLoader>();
var bitmap = new Bitmap(assets.Open(new Uri(uri)));
uri variable in the snippet can contain any valid URI, including
resm: as described above. By default, Avalonia does not provide support for
https:// schemes. If you want to load files from disk or web, you can implement that functionality yourself or use community implementations like https://github.com/AvaloniaUtils/AsyncImageLoader.Avalonia.