Create a hyperlink using Xamarin.Forms (xaml and c#)

I made this little class to handle it:

public class SimpleLinkLabel : Label
{
    public SimpleLinkLabel(Uri uri, string labelText = null)
    {
        Text = labelText ?? uri.ToString();
        TextColor = Color.Blue;
        GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => Device.OpenUri(uri)) });
    }
}

And a bit more involved if you want to underline it too:

public class LinkLabel : StackLayout
{
    private SimpleLinkLabel label;

    public LinkLabel(Uri uri, string labelText = null, bool underlined = true)
    {
        // Remove bottom padding
        Padding = new Thickness(Padding.Left, Padding.Top, Padding.Right, 0);
        VerticalOptions = LayoutOptions.Center;

        Children.Add(label = new SimpleLinkLabel(uri, labelText));

        if (underlined)
            Children.Add(new BoxView { BackgroundColor = Color.Blue, HeightRequest = 1, Margin = new Thickness(0, -8, 0, 0) });
    }

    public TextAlignment HorizontalTextAlignment { get { return label.HorizontalTextAlignment; } set { label.HorizontalTextAlignment = value; } }
}

The latter class inspired by this post: how to underline in xamarin forms


Edit: XLabs have a HyperLinkLabel too.


<Label LineBreakMode="WordWrap">
    <Label.FormattedText>
        <FormattedString>
            <Span Text="Google">
                <Span.GestureRecognizers>
                    <TapGestureRecognizer Tapped="Handle_Tapped" />
                </Span.GestureRecognizers>
            </Span>
        </FormattedString>
    </Label.FormattedText>
</Label>
public async void Handle_Tapped(object sender, EventArgs e)
{
    await Browser.OpenAsync(new Uri(url), BrowserLaunchMode.SystemPreferred);
}

You can't really do this because Labels by default don't respond to user input, but you can achieve something similar with gestures

using Xamarin.Forms;
using Xamarin.Essentials;

Label label = new Label();
label.Text = "http://www.google.com/";

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += async (s, e) => {
    // Depreciated - Device.OpenUri( new Uri((Label)s).Text); 
    await Launcher.OpenAsync(new Uri(((Label)s).Text));
};
label.GestureRecognizers.Add(tapGestureRecognizer);