Make MarkupExtension work with Hot Reload (Xamarin)

176 views Asked by At

Title says the most. I have a custom MarkupExtension which gets an icon with a provided name from a font and returns it as a FontImageSource. The extension can be used anywhere where ImageSources can be used. The extension by itself works pretty fine. Only problem is when I use hot reload, do some changes on my page and the view gets reloaded by saving the changes, all controls (e.g. Image) that use my extension are blank.

Is there any way to get my MarkupExtension to work with Hot Reload?

Example code:

[ContentProperty(nameof(IconName))]
public class FontImageExtension : IMarkupExtension<ImageSource>
{
    private readonly IconFontService iconFontService;

    public string IconName { get; set; }

    public FontImageExtension()
    {
        iconFontService = GetService();
    }

    public ImageSource ProvideValue(IServiceProvider serviceProvider)
    {
        if (string.IsNullOrEmpty(IconName))
            return null;

        string glyphCode = iconFontService.GetGlyphCode(IconName);

        if (string.IsNullOrEmpty(glyphCode))
            return null;

        return new FontImageSource()
        {
            FontFamily = iconFontService.GetFontLocation(),
            Glyph = glyphCode,
        };
    }

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        // Converting back is not needed
        return null;
    }
}
1

There are 1 answers

0
Christoph Mett On

Oh wow, I'm the dumbest guy ever. The function IMarkupExtension.ProvideValue is not for providing a way to to convert the ImageSource back into whatever (don't know why I assumed it did). This seems to be the function that is called on hot reload.

So the answer is as easy as changing IMarkupExtension.ProvideValue to the following:

object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
{
    return ProvideValue(serviceProvider);
}