Friday, March 17, 2017

[Code Sample] Image From Resource - IMarkupExtension

This extension allows to set image in XAML from resource images.

1. Extension code
   [ContentProperty("Source")]
    public class ImageResourceExtension : IMarkupExtension
    {
        public string Source { get; set; }
        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Source == null)
            {
                return null;
            }
            var imageSource = ImageSource.FromResource("MobileApp.Images." + Source);
            return imageSource;
        }
    }
2. Add namespace
 xmlns:resources="clr-namespace:MobileApp.Resources;assembly=MobileApp" 
3. Usage
 <Image Source="{resources:ImageResource  image.png}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Aspect="Fill"  />
    

No comments:

Post a Comment