How to refer to Embedded Resources from XAML?

╄→尐↘猪︶ㄣ 提交于 2019-11-27 23:28:20
yo chauhan

When you set the BuildAction to Resource it goes as embedded resource in an assembly. Or you can set BuildAction to Content then it will bundled into the resulting .xap file. You can use any one of these BuildActions. By setting BuildAction to Content you can access Image like: "/Resources/Images/darkaurora.png" (must begin with slash). And when you use the BuildAction Resource then you can access image as "/YearBook;component/Resources/Images/darkaurora.png" (assemblyname;component/relativepath). Hope this will help.

Set the build action to Resource, not Embedded Resource

ImageSource cannot be instantiated.

public abstract class ImageSource : Animatable, 
IFormattable

There's that little abstract in there which will screw your day up. Your xaml is actually trying to instantiate an instance of ImageSource, then assign the value within the element (your Uri, in this case) to a property marked with the ContentPropertyAttribute (??) using whatever converter that could be located to convert the string to an object (again, ??).

I think you want a BitmapSource.

<BitmapImage 
    x:Key="Image_Background" 
    UriSource="/Images/darkaurora.png" />

Just for those using xamarin forms and bump into this question, this can be done by creating a custom xaml markup extension explained here:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=windows

in the "Embedded Images"->"Using XAML" section

Citation of custom extension

[ContentProperty (nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
 public string Source { get; set; }

 public object ProvideValue (IServiceProvider serviceProvider)
 {
   if (Source == null)
   {
     return null;
   }

   // Do your translation lookup here, using whatever method you require
   var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);

   return imageSource;
 }
}

citation of how to use

<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:local="clr-namespace:WorkingWithImages;assembly=WorkingWithImages"
   x:Class="WorkingWithImages.EmbeddedImagesXaml">
 <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
   <!-- use a custom Markup Extension -->
   <Image Source="{local:ImageResource WorkingWithImages.beach.jpg}" />
 </StackLayout>
</ContentPage>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!