使用Xamarin.Forms(xaml和c#)创建超链接

jne*_*899 20 c# xaml xamarin.ios xamarin xamarin.forms

我是一个相对缺乏经验的专业程序员(我只有20岁).因此,我提前道歉,因为可能有一些我还没有完全掌握的更大的概念.我希望这是一个适当的问题,因为一小时的谷歌搜索无法帮助我.

我基本上想要使用标签类在Xamarin.Forms中创建一个超链接.基本上,我想关注链接以将用户带到网络浏览器中的google.com:

<Label Text="http://www.google.com/" />
Run Code Online (Sandbox Code Playgroud)

我在Xamarin Forms API中找不到任何关于此的内容,互联网在Xamarin.Forms中有关于此主题的模糊且有限的信息.

这可能吗?如果是这样,有人可以指出我正确的方向吗?提前感谢任何回答的人.

Jas*_*son 23

你不能真的这样做,因为默认情况下标签不响应用户输入,但你可以通过手势实现类似的功能

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

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) => {
    Device.OpenUri( new Uri((Label)s).Text);
};
label.GestureRecognizers.Add(tapGestureRecognizer);
Run Code Online (Sandbox Code Playgroud)


noe*_*cus 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)) });
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想强调它也会涉及更多:

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; } }
}
Run Code Online (Sandbox Code Playgroud)

后一课的灵感来自这篇文章:如何强调xamarin形式


编辑:XLabs也有HyperLinkLabel.


use*_*249 6

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