简体   繁体   中英

Make MarkupExtension work with Hot Reload (Xamarin)

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 (eg 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;
    }
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM