Xamarin.Forms Resolving System.Reflection.TargetException

Setting an image in your Xamarin.Forms project is easily done when setting the image as embedded resource since instead of having a copy of the image in each application’s file structure the image file is embedded in the assembly as a resource. According to this documentation, it is done easily as follows:

var embeddedImage = new Image { Source = ImageSource.FromResource("ImagesProj.beach.jpg") };

I succeeded in adding images into my Xamarin.Forms projects using this method a while ago on earlier versions of Xamarin.Forms. But recently, I got an issue when trying this again on Xamarin.Forms and .Net standard 2.0 as my shared project. This issue was System.Reflection.TargetException. This was a pain in the 🤬. But, it wasn’t that difficult to resolve.

Don’t miss any post and subscribe to the mailing list

Cool Coders

After researching online, I found a solution. What you need to do is call the image as follows:

 var assembly = typeof(TypeInProjectAssembly).Assembly;
Img.Source = ImageSource.FromResource(@"Project.Images.Image.png", assembly)

Where TypeInProjectAssembly is any type in your current project’s assembly. and Project.Images.Image.png refers to the Default namespace of the project and the file path separated by periods (.).

From here, you may have resolved you issue already, but don’t forget, the image should have a buld action of Embedded resource.

After doing all this, I though the problem would have been resolved by now but, when running the project on its different platforms, I noticed the image wasn’t displyaed. If this happen’s to you, open your .csproj file in edit mode. Check if your image was correctly added as embedded resource and check LogicalName attribute, if it is present or if it matches what you have in your code (in my case this value is Project.Images.Image.png). If it doesn’t match or it is not present, add it your self as follows:

   <EmbeddedResource Include="Images\Image.png">

After doing all this, you should have resolved this issue.

Cool Coders

If you liked this post, or it was useful to you, please 👍 like it, share it on twitter, facebook or other social media… in case you want to get updated on any new useful post, follow me on twitter,  Github  and like my page on facebook. And every other social media by clicking on the  buttons at the end of this post.

Follow me on social media and stay updated

Check how to build a simple android camera app with Xamarin.Android here.

Follow me on social media and stay updated