使用Xamarin.Forms(XAML和C#)创建超链接

24

我想在Xamarin.Forms中使用label类创建一个超链接。我希望这个链接可以将用户带到浏览器中的google.com:

<Label Text="http://www.google.com/" />

我在Xamarin Forms API中找不到任何关于这个问题的信息,而且互联网上关于Xamarin.Forms这个主题的信息含糊不清、有限。

这种情况可能存在吗?如果可以,能否有人指点一下方向?谢谢提前回答的任何人。


1
在Xamarin Forms上本身并没有链接,只需向标签添加GestureListener,并自行启动浏览器即可。 - Gusman
2
可能是HyperlinkButton in C# XAMARIN.FORMS的重复问题。 - JKennedy
The TapGestureRecognizer也接受命令。 纯模板的不错解决方案。 - HCL
5个回答

23

由于默认情况下标签不会响应用户输入,因此您无法真正地做到这一点,但是您可以通过手势实现类似的效果。

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

1
非常感谢!我需要进行一个小修正:实际上应该是 Device.OpenUri(new Uri(((Label)s).Text));,使用 new Uri(uriString) 构造函数可以将字符串初始化为 Uri。谢谢,在更改后它可以工作了! - jnel899
1
由于OpenUri已被弃用,您现在应该编写Launcher.OpenAsync(new Uri((s as Label).Text)); - Adriano
@Adriano 谢谢 - 我已经提交了一个反映这个的编辑。 - jnel899

10

我做了这个小类来处理它:

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

如果你想要添加下划线,那就需要更加复杂一些:

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

后一类灵感来自于这篇帖子:如何在 Xamarin Forms 中添加下划线


编辑:XLabs 也有一个HyperLinkLabel


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

5

3

如果你想使用MVVM来实现这个功能,你可以创建一个带有蓝色文本颜色的标签,并添加一个GestureRecognizers,将其连接到一个命令(Command)上:

<Label TextColor="Blue" Text="{Binding Model.LinkDescription}">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding ClickCommand}" CommandParameter="{Binding Model.LinkURL}"/>
    </Label.GestureRecognizers>
</Label>

在您的ViewModel中,您可以使用Xamarin Essentials Nuget包启动默认浏览器:

private Boolean IsValidUri(String uri)
{
    try
    {
        new Uri(uri);
        return true;
    }
    catch
    {
        return false;
    }
}

public ICommand ClickCommand => new Command<string>(async (url) =>
{
    try
    {
        if (!string.IsNullOrEmpty(url))
        {
            if (!url.Trim().StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                url = "http://" + url;
            }
            if (IsValidUri(url))
            {
                await Browser.OpenAsync(new Uri(url), BrowserLaunchMode.SystemPreferred);
            }
        }
    }
    catch(Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接