首页 文章

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

提问于
浏览
16

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

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

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

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

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

3 回答

  • 18

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

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

    使用按钮和xamarin.forms.theme nuget

    <Button StyleClass = "Link"/>
    

    https://developer.xamarin.com/guides/xamarin-forms/user-interface/themes/light/

  • 4

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

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

    后一课的灵感来自这篇文章:how to underline in xamarin forms


    编辑:XLabs也有HyperLinkLabel .

相关问题