This is a useful helper class for Xamarin.Forms that will allow you to easily reference a file asset that is tagged as an Embedded Resource easily from your XAML mark-up. This is taken from the Xamarin.Forms documentation and modified slightly because I was having issues with it properly loading the resource files after upgrading to the latest version.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | [Xamarin.Forms.Internals.Preserve(AllMembers = true)] [Xamarin.Forms.ContentProperty(nameof(Source))] class ImageResourceExtension : Xamarin.Forms.Xaml.IMarkupExtension { public String Source { get; set; } // Store out the current assembly to use for referencing the resources private static System.Reflection.Assembly execAssembly = System.Reflection.Assembly.GetExecutingAssembly(); public object ProvideValue(IServiceProvider serviceProvider) { Xamarin.Forms.ImageSource imageSource = null; try { if (!String.IsNullOrEmpty(Source)) { // Load the named resource file from the current executing assembly imageSource = Xamarin.Forms.ImageSource.FromResource(Source, execAssembly); } } catch (Exception err) { System.Diagnostics.Debug.WriteLine(err.Message); } return imageSource; } } |
Once that is in place, you use it the same as the Xamarin.Forms documentation:
- Add a custom xmlns to your XAML page referencing your namespace and assembly:1xmlns:local="clr-namespace:MyNameSpace;assembly=MyAssembly"
- Use your custom xmlns as the source for your Image1<Image Aspect="AspectFit" Source="{local:ImageResource MyNamespaceForResources.filename.ext}"></Image>
(keep in mind that if you created a folder for your embedded resources, that will be part of the resource namespace)