Xamarin 标签Xamarin.Forms Label

下载示例 下载示例Download Sample Download the sample

在 Xamarin. Forms 中显示文本Display text in Xamarin.Forms

" Label " 视图用于显示文本(单行和多行)。The Label view is used for displaying text, both single and multi-line. 标签可以具有文本修饰、彩色文本和使用自定义字体(系列、大小和选项)。Labels can have text decorations, colored text, and use custom fonts (families, sizes, and options).

文本修饰Text decorations

可以通过将 Label.TextDecorations 属性设置为一个或多个 TextDecorations 枚举成员,将下划线和删除线文本修饰应用于Label实例:Underline and strikethrough text decorations can be applied to Label instances by setting the Label.TextDecorations property to one or more TextDecorations enumeration members:

  • None
  • Underline
  • Strikethrough

下面的 XAML 示例演示如何设置 Label.TextDecorations 属性:The following XAML example demonstrates setting the Label.TextDecorations property:

<Label Text="This is underlined text." TextDecorations="Underline"  />
<Label Text="This is text with strikethrough." TextDecorations="Strikethrough" />
<Label Text="This is underlined text with strikethrough." TextDecorations="Underline, Strikethrough" />

等效 C# 代码如下:The equivalent C# code is:

var underlineLabel = new Label { Text = "This is underlined text.", TextDecorations = TextDecorations.Underline };
var strikethroughLabel = new Label { Text = "This is text with strikethrough.", TextDecorations = TextDecorations.Strikethrough };
var bothLabel = new Label { Text = "This is underlined text with strikethrough.", TextDecorations = TextDecorations.Underline | TextDecorations.Strikethrough };

以下屏幕截图显示了应用于Label实例的 TextDecorations 枚举成员:The following screenshots show the TextDecorations enumeration members applied to Label instances:

带有文本修饰的标签

备注

还可以对Span实例应用文本修饰。Text decorations can also be applied to Span instances. 有关 Span 类的详细信息,请参阅格式化文本For more information about the Span class, see Formatted Text.

字符间距Character spacing

可以通过将 Label.CharacterSpacing 属性设置为 double 值,将字符间距应用到Label实例:Character spacing can be applied to Label instances by setting the Label.CharacterSpacing property to a double value:

<Label Text="Character spaced text"
       CharacterSpacing="10" />

等效 C# 代码如下:The equivalent C# code is:

Label label = new Label { Text = "Character spaced text", CharacterSpacing = 10 };

结果是Label显示的文本中的字符间距 CharacterSpacing 与设备无关的单位。The result is that characters in the text displayed by the Label are spaced CharacterSpacing device-independent units apart.

颜色Colors

可以通过可绑定的TextColor属性将标签设置为使用自定义文本颜色。Labels can be set to use a custom text color via the bindable TextColor property.

需要特别注意,以确保每个平台的颜色都可用。Special care is necessary to ensure that colors will be usable on each platform. 由于每个平台对于文本和背景色都具有不同的默认值,因此,需要小心选取每个平台的默认值。Because each platform has different defaults for text and background colors, you'll need to be careful to pick a default that works on each.

下面的 XAML 示例设置 Label 的文本颜色:The following XAML example sets the text color of a Label:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TextSample.LabelPage"
             Title="Label Demo">
    <StackLayout Padding="5,10">
      <Label TextColor="#77d065" FontSize = "20" Text="This is a green label." />
    </StackLayout>
</ContentPage>

等效 C# 代码如下:The equivalent C# code is:

public partial class LabelPage : ContentPage
{
    public LabelPage ()
    {
        InitializeComponent ();

        var layout = new StackLayout { Padding = new Thickness(5,10) };
        var label = new Label { Text="This is a green label.", TextColor = Color.FromHex("#77d065"), FontSize = 20 };
        layout.Children.Add(label);
        this.Content = layout;
    }
}

以下屏幕截图显示设置 TextColor 属性的结果:The following screenshots show the result of setting the TextColor property:

标签 TextColor 示例

有关颜色的详细信息,请参阅颜色For more information about colors, see Colors.

字体Fonts

有关在 Label 上指定字体的详细信息,请参阅字体For more information about specifying fonts on a Label, see Fonts.

截断和换行Truncation and wrapping

可以通过 LineBreakMode 属性公开的多种方式之一来设置标签来处理无法容纳在一个行中的文本。Labels can be set to handle text that can't fit on one line in one of several ways, exposed by the LineBreakMode property. LineBreakMode是具有以下值的枚举:LineBreakMode is an enumeration with the following values:

  • HeadTruncation – 截断文本开头,并显示结束。HeadTruncation – truncates the head of the text, showing the end.
  • CharacterWrap – 将文本包装到字符边界处的新行中。CharacterWrap – wraps text onto a new line at a character boundary.
  • MiddleTruncation – 显示文本的开头和结尾,中间用省略号替换。MiddleTruncation – displays the beginning and end of the text, with the middle replace by an ellipsis.
  • NoWrap – 不会自动换行,只显示一行中可容纳的最多文本。NoWrap – does not wrap text, displaying only as much text as can fit on one line.
  • TailTruncation – 显示文本的开头,从而截断结束。TailTruncation – shows the beginning of the text, truncating the end.
  • 换行– 在字边界处环绕文本。WordWrap – wraps text at the word boundary.

显示特定行数Display a specific number of lines

可以通过将 Label.MaxLines 属性设置为 int 值来指定Label显示的行数:The number of lines displayed by a Label can be specified by setting the Label.MaxLines property to a int value:

  • MaxLines 为0时,Label 会考虑LineBreakMode属性的值,使其只显示一行(可能已截断)或包含所有文本的所有行。When MaxLines is 0, the Label respects the value of the LineBreakMode property to either show just one line, possibly truncated, or all lines with all text.
  • 如果 MaxLines 为1,则结果与将LineBreakMode属性设置为NoWrapHeadTruncationMiddleTruncation0完全相同。When MaxLines is 1, the result is identical to setting the LineBreakMode property to NoWrap, HeadTruncation, MiddleTruncation, or TailTruncation. 但是,Label 将遵循省略号的位置(如果适用)的LineBreakMode属性的值。However, the Label will respect the value of the LineBreakMode property with regard to placement of an ellipsis, if applicable.
  • MaxLines 大于1时,Label 将显示到指定的行数,同时遵循省略号的位置(如果适用)的LineBreakMode属性的值。When MaxLines is greater than 1, the Label will display up to the specified number of lines, while respecting the value of the LineBreakMode property with regard to placement of an ellipsis, if applicable. 但是,如果将LineBreakMode属性设置为NoWrap,则将 MaxLines 属性设置为大于1的值将不起作用。However, setting the MaxLines property to a value greater than 1 has no effect if the LineBreakMode property is set to NoWrap.

下面的 XAML 示例演示如何设置Label上的 MaxLines 属性:The following XAML example demonstrates setting the MaxLines property on a Label:

<Label Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus."
       LineBreakMode="WordWrap"
       MaxLines="2" />

等效 C# 代码如下:The equivalent C# code is:

var label =
{
  Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus.", LineBreakMode = LineBreakMode.WordWrap,
  MaxLines = 2
};

下面的屏幕截图显示将 MaxLines 属性设置为2(当文本足够长,超过2行时)的结果:The following screenshots show the result of setting the MaxLines property to 2, when the text is long enough to occupy more than 2 lines:

标签 MaxLines 示例

显示 HTMLDisplay HTML

Label类具有一个 TextType 属性,该属性确定 Label 实例是否应显示纯文本或 HTML 文本。The Label class has a TextType property, which determines whether the Label instance should display plain text, or HTML text. 应将此属性设置为 TextType 枚举的成员之一:This property should be set to one of the members of the TextType enumeration:

  • Text 指示 Label 将显示纯文本,并且是 Label.TextType 属性的默认值。Text indicates that the Label will display plain text, and is the default value of the Label.TextType property.
  • Html 指示 Label 将显示 HTML 文本。Html indicates that the Label will display HTML text.

因此, Label实例可以通过将 Label.TextType 属性设置为 Html,并将 Label.Text 属性设置为 html 字符串来显示 html:Therefore, Label instances can display HTML by setting the Label.TextType property to Html, and the Label.Text property to a HTML string:

Label label = new Label
{
    Text = "This is <strong style=\"color:red\">HTML</strong> text.",
    TextType = TextType.Html
};

在上面的示例中,HTML 中的双引号字符必须使用 \ 符号进行转义。In the example above, the double quote characters in the HTML have to be escaped using the \ symbol.

在 XAML 中,HTML 字符串会由于另外转义 <> 符号而变得不可读:In XAML, HTML strings can become unreadable due to additionally escaping the < and > symbols:

<Label Text="This is &lt;strong style=&quot;color:red&quot;&gt;HTML&lt;/strong&gt; text."
       TextType="Html"  />

另外,为了提高可读性,可以在 CDATA 部分中内联 HTML:Alternatively, for greater readability the HTML can be inlined in a CDATA section:

<Label TextType="Html">
    <x:String>
        <![CDATA[
        This is <strong style="color:red">HTML</strong> text.
        ]]>
    </x:String>
</Label>

在此示例中,Label.Text 属性设置为在 CDATA 部分中内联的 HTML 字符串。In this example, the Label.Text property is set to the HTML string that's inlined in the CDATA section. 这是因为 Text 属性是 Label 类的 ContentPropertyThis works because the Text property is the ContentProperty for the Label class.

以下屏幕截图显示了一个Label显示 HTML:The following screenshots show a Label displaying HTML:

在 iOS 和 Android 上显示 HTML 的标签的屏幕截图

重要

Label中显示 html 仅限于底层平台支持的 html 标记。Displaying HTML in a Label is limited to the HTML tags that are supported by the underlying platform.

带格式文本Formatted text

标签公开一个FormattedText属性,该属性允许在同一视图中显示具有多种字体和颜色的文本。Labels expose a FormattedText property that allows the presentation of text with multiple fonts and colors in the same view.

FormattedText 属性的类型FormattedString,它包含一个或多个Span实例,通过Spans属性进行设置。The FormattedText property is of type FormattedString, which comprises one or more Span instances, set via the Spans property. 以下 Span 属性可用于设置视觉外观:The following Span properties can be used to set visual appearance:

  • BackgroundColor –跨度背景的颜色。BackgroundColor – the color of the span background.
  • CharacterSpacing 类型 double,是 Span 文本的字符之间的间距。CharacterSpacing, of type double, is the spacing between characters of the Span text.
  • Font –跨度中的文本的字体。Font – the font for the text in the span.
  • FontAttributes –跨度中的文本的字体属性。FontAttributes – the font attributes for the text in the span.
  • FontFamily –范围中的文本的字体所属的字体系列。FontFamily – the font family to which the font for the text in the span belongs.
  • FontSize –范围中文本的字体大小。FontSize – the size of the font for the text in the span.
  • ForegroundColor –范围中文本的颜色。ForegroundColor – the color for the text in the span. 此属性已过时,已被 TextColor 属性替换。This property is obsolete and has been replaced by the TextColor property.
  • LineHeight -要应用于范围默认行高的乘数。LineHeight - the multiplier to apply to the default line height of the span. 有关详细信息,请参阅行高For more information, see Line Height.
  • Style –应用于范围的样式。Style – the style to apply to the span.
  • Text –范围的文本。Text – the text of the span.
  • TextColor –范围中文本的颜色。TextColor – the color for the text in the span.
  • TextDecorations-要应用于范围中的文本的修饰。TextDecorations - the decorations to apply to the text in the span. 有关详细信息,请参阅文本修饰For more information, see Text Decorations.

BackgroundColorTextText可绑定属性的默认绑定模式为OneWayThe BackgroundColor, Text, and Text bindable properties have a default binding mode of OneWay. 有关此绑定模式的详细信息,请参阅绑定模式指南中的默认绑定模式For more information about this binding mode, see The Default Binding Mode in the Binding Mode guide.

此外, GestureRecognizers属性可以用于定义将响应Span上的手势的笔势识别器的集合。In addition, the GestureRecognizers property can be used to define a collection of gesture recognizers that will respond to gestures on the Span.

备注

无法在Span中显示 HTML。It's not possible to display HTML in a Span.

下面的 XAML 示例说明了包含三个Span实例的 FormattedText 属性:The following XAML example demonstrates a FormattedText property that consists of three Span instances:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TextSample.LabelPage"
             Title="Label Demo - XAML">
    <StackLayout Padding="5,10">
        ...
        <Label LineBreakMode="WordWrap">
            <Label.FormattedText>
                <FormattedString>
                    <Span Text="Red Bold, " TextColor="Red" FontAttributes="Bold" />
                    <Span Text="default, " Style="{DynamicResource BodyStyle}">
                        <Span.GestureRecognizers>
                            <TapGestureRecognizer Command="{Binding TapCommand}" />
                        </Span.GestureRecognizers>
                    </Span>
                    <Span Text="italic small." FontAttributes="Italic" FontSize="Small" />
                </FormattedString>
            </Label.FormattedText>
        </Label>
    </StackLayout>
</ContentPage>

等效 C# 代码如下:The equivalent C# code is:

public class LabelPageCode : ContentPage
{
    public LabelPageCode ()
    {
        var layout = new StackLayout{ Padding = new Thickness (5, 10) };
        ...
        var formattedString = new FormattedString ();
        formattedString.Spans.Add (new Span{ Text = "Red bold, ", ForegroundColor = Color.Red, FontAttributes = FontAttributes.Bold });

        var span = new Span { Text = "default, " };
        span.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(async () => await DisplayAlert("Tapped", "This is a tapped Span.", "OK")) });
        formattedString.Spans.Add(span);
        formattedString.Spans.Add (new Span { Text = "italic small.", FontAttributes = FontAttributes.Italic, FontSize =  Device.GetNamedSize(NamedSize.Small, typeof(Label)) });

        layout.Children.Add (new Label { FormattedText = formattedString });
        this.Content = layout;
    }
}

重要

可以通过数据绑定来设置 SpanText属性。The Text property of a Span can be set through data binding. 有关详细信息,请参阅数据绑定For more information, see Data Binding.

请注意, Span还可以响应添加到跨距GestureRecognizers集合的任何手势。Note that a Span can also respond to any gestures that are added to the span's GestureRecognizers collection. 例如,在上面的代码示例中,已将TapGestureRecognizer添加到第二个 SpanFor example, a TapGestureRecognizer has been added to the second Span in the above code examples. 因此,当点击此 Span 时,TapGestureRecognizer 将通过执行Command属性定义的 ICommand 来做出响应。Therefore, when this Span is tapped the TapGestureRecognizer will respond by executing the ICommand defined by the Command property. 有关手势识别器的详细信息,请参阅Xamarin。For more information about gesture recognizers, see Xamarin.Forms Gestures.

以下屏幕截图显示将 FormattedString 属性设置为三个 Span 实例的结果:The following screenshots show the result of setting the FormattedString property to three Span instances:

标签 FormattedText 示例

行高Line height

可以通过将Label.LineHeight属性或Span.LineHeight设置为 double 值来自定义LabelSpan的垂直高度。The vertical height of a Label and a Span can be customized by setting the Label.LineHeight property or Span.LineHeight to a double value. 在 iOS 和 Android 上,这些值为原始行高的乘数,在通用 Windows 平台(UWP)上,Label.LineHeight 属性值为标签字体大小的乘数。On iOS and Android these values are multipliers of the original line height, and on the Universal Windows Platform (UWP) the Label.LineHeight property value is a multiplier of the label font size.

备注

下面的 XAML 示例演示如何设置Label上的LineHeight属性:The following XAML example demonstrates setting the LineHeight property on a Label:

<Label Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus."
       LineBreakMode="WordWrap"
       LineHeight="1.8" />

等效 C# 代码如下:The equivalent C# code is:

var label =
{
  Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus.", LineBreakMode = LineBreakMode.WordWrap,
  LineHeight = 1.8
};

以下屏幕截图显示将Label.LineHeight属性设置为1.8 的结果:The following screenshots show the result of setting the Label.LineHeight property to 1.8:

标签 LineHeight 示例

下面的 XAML 示例演示如何设置Span上的LineHeight属性:The following XAML example demonstrates setting the LineHeight property on a Span:

<Label LineBreakMode="WordWrap">
    <Label.FormattedText>
        <FormattedString>
            <Span Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a tincidunt sem. Phasellus mollis sit amet turpis in rutrum. Sed aliquam ac urna id scelerisque. "
                  LineHeight="1.8"/>
            <Span Text="Nullam feugiat sodales elit, et maximus nibh vulputate id."
                  LineHeight="1.8" />
        </FormattedString>
    </Label.FormattedText>
</Label>

等效 C# 代码如下:The equivalent C# code is:

var formattedString = new FormattedString();
formattedString.Spans.Add(new Span
{
  Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a tincidunt sem. Phasellus mollis sit amet turpis in rutrum. Sed aliquam ac urna id scelerisque. ",
  LineHeight = 1.8
});
formattedString.Spans.Add(new Span
{
  Text = "Nullam feugiat sodales elit, et maximus nibh vulputate id.",
  LineHeight = 1.8
});
var label = new Label
{
  FormattedText = formattedString,
  LineBreakMode = LineBreakMode.WordWrap
};

以下屏幕截图显示将Span.LineHeight属性设置为1.8 的结果:The following screenshots show the result of setting the Span.LineHeight property to 1.8:

Span LineHeight 示例

填充Padding

填充表示元素及其子元素之间的空间,用于将元素与其自身内容分离。Padding represents the space between an element and its child elements, and is used to separate the element from its own content. 可以通过将 Label.Padding 属性设置为Thickness值,将填充应用到Label实例:Padding can be applied to Label instances by setting the Label.Padding property to a Thickness value:

<Label Padding="10">
    <Label.FormattedText>
        <FormattedString>
            <Span Text="Lorem ipsum" />
            <Span Text="dolor sit amet." />
        </FormattedString>
    </Label.FormattedText>
</Label>

等效 C# 代码如下:The equivalent C# code is:

FormattedString formattedString = new FormattedString();
formattedString.Spans.Add(new Span
{
  Text = "Lorem ipsum"
});
formattedString.Spans.Add(new Span
{
  Text = "dolor sit amet."
});
Label label = new Label
{
    FormattedText = formattedString,
    Padding = new Thickness(20)
};

重要

在 iOS 上,当创建设置 Padding 属性的Label时,将应用填充,并且可以在以后更新填充值。On iOS, when a Label is created that sets the Padding property, padding will be applied and the padding value can be updated later. 但是,如果创建的 Label 不设置 Padding 属性,稍后尝试设置该属性将不起作用。However, when a Label is created that doesn't set the Padding property, attempting to set it later will have no effect.

在 Android 和通用 Windows 平台上,可以在创建 Label 或更高版本时指定 Padding 属性值。On Android and the Universal Windows Platform, the Padding property value can be specified when the Label is created, or later.

有关填充的详细信息,请参阅边距和填充For more information about padding, see Margins and Padding.

LabelSpan实例显示的文本可以通过以下方法转换为超链接:The text displayed by Label and Span instances can be turned into hyperlinks with the following approach:

  1. 设置LabelSpan的 "TextColor" 和 "TextDecoration" 属性。Set the TextColor and TextDecoration properties of the Label or Span.
  2. TapGestureRecognizer添加到LabelSpanGestureRecognizers集合,其Command属性绑定到 0,其2属性包含要打开的 URL。Add a TapGestureRecognizer to the GestureRecognizers collection of the Label or Span, whose Command property binds to a ICommand, and whose CommandParameter property contains the URL to open.
  3. 定义将由TapGestureRecognizer执行的 ICommandDefine the ICommand that will be executed by the TapGestureRecognizer.
  4. 编写 ICommand 将执行的代码。Write the code that will be executed by the ICommand.

以下从 "超链接演示" 示例获取的代码示例显示了从多个Span实例设置内容的LabelThe following code example, taken from the Hyperlink Demos sample, shows a Label whose content is set from multiple Span instances:

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span Text="Alternatively, click " />
            <Span Text="here"
                  TextColor="Blue"
                  TextDecorations="Underline">
                <Span.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding TapCommand}"
                                          CommandParameter="https://docs.microsoft.com/xamarin/" />
                </Span.GestureRecognizers>
            </Span>
            <Span Text=" to view Xamarin documentation." />
        </FormattedString>
    </Label.FormattedText>
</Label>

在此示例中,第一个和第三个Span实例包含文本,第二个 Span 表示 tappable 超链接。In this example, the first and third Span instances comprise text, while the second Span represents a tappable hyperlink. 它的文本颜色设置为蓝色,并且具有下划线文本修饰。It has its text color set to blue, and has an underline text decoration. 这会创建超链接的外观,如以下屏幕截图所示:This creates the appearance of a hyperlink, as shown in the following screenshots:

中超Hyperlinks

点击超链接时, TapGestureRecognizer将通过执行其Command属性定义的 ICommand 来做出响应。When the hyperlink is tapped, the TapGestureRecognizer will respond by executing the ICommand defined by its Command property. 此外, CommandParameter属性指定的 URL 将作为参数传递给 ICommandIn addition, the URL specified by the CommandParameter property will be passed to the ICommand as a parameter.

XAML 页的代码隐藏包含 TapCommand 实现:The code-behind for the XAML page contains the TapCommand implementation:

public partial class MainPage : ContentPage
{
    // Launcher.OpenAsync is provided by Xamarin.Essentials.
    public ICommand TapCommand => new Command<string>(async (url) => await Launcher.OpenAsync(url));

    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
    }
}

TapCommand 执行 Launcher.OpenAsync 方法,并将TapGestureRecognizer.CommandParameter属性值作为参数传递。The TapCommand executes the Launcher.OpenAsync method, passing the TapGestureRecognizer.CommandParameter property value as a parameter. Launcher.OpenAsync 方法由 Xamarin 提供,并在 web 浏览器中打开该 URL。The Launcher.OpenAsync method is provided by Xamarin.Essentials, and opens the URL in a web browser. 因此,整体效果是,当在页面上点击超链接时,将显示一个 web 浏览器,并导航到与该超链接关联的 URL。Therefore, the overall effect is that when the hyperlink is tapped on the page, a web browser appears and the URL associated with the hyperlink is navigated to.

创建超链接的前一种方法需要在应用程序中每次需要超链接时编写重复代码。The previous approach to creating a hyperlink requires writing repetitive code every time you require a hyperlink in your application. 不过, LabelSpan类都可以是子类,以创建 HyperlinkLabelHyperlinkSpan 类,并在其中添加了手势识别器和文本格式代码。However, both the Label and Span classes can be subclassed to create HyperlinkLabel and HyperlinkSpan classes, with the gesture recognizer and text formatting code added there.

下面的代码示例摘自Hyperlink 演示示例,其中显示了一个 HyperlinkSpan 类:The following code example, taken from the Hyperlink Demos sample, shows a HyperlinkSpan class:

public class HyperlinkSpan : Span
{
    public static readonly BindableProperty UrlProperty =
        BindableProperty.Create(nameof(Url), typeof(string), typeof(HyperlinkSpan), null);

    public string Url
    {
        get { return (string)GetValue(UrlProperty); }
        set { SetValue(UrlProperty, value); }
    }

    public HyperlinkSpan()
    {
        TextDecorations = TextDecorations.Underline;
        TextColor = Color.Blue;
        GestureRecognizers.Add(new TapGestureRecognizer
        {
            // Launcher.OpenAsync is provided by Xamarin.Essentials.
            Command = new Command(async () => await Launcher.OpenAsync(Url))
        });
    }
}

HyperlinkSpan 类定义 Url 属性和关联的BindableProperty,并且构造函数会设置超链接的外观,以及在点击超链接时将响应的TapGestureRecognizerThe HyperlinkSpan class defines a Url property, and associated BindableProperty, and the constructor sets the hyperlink appearance and the TapGestureRecognizer that will respond when the hyperlink is tapped. 点击 HyperlinkSpan 时,TapGestureRecognizer 将通过执行 Launcher.OpenAsync 方法,在 web 浏览器中打开 Url 属性指定的 URL 来做出响应。When a HyperlinkSpan is tapped, the TapGestureRecognizer will respond by executing the Launcher.OpenAsync method to open the URL, specified by the Url property, in a web browser.

可以通过将类的实例添加到 XAML 来使用 HyperlinkSpan 类:The HyperlinkSpan class can be consumed by adding an instance of the class to the XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:HyperlinkDemo"
             x:Class="HyperlinkDemo.MainPage">
    <StackLayout>
        ...
        <Label>
            <Label.FormattedText>
                <FormattedString>
                    <Span Text="Alternatively, click " />
                    <local:HyperlinkSpan Text="here"
                                         Url="https://docs.microsoft.com/appcenter/" />
                    <Span Text=" to view AppCenter documentation." />
                </FormattedString>
            </Label.FormattedText>
        </Label>
    </StackLayout>
</ContentPage>

设置标签样式Styling labels

前面几节介绍了如何根据每个实例设置LabelSpan属性。The previous sections covered setting Label and Span properties on a per-instance basis. 但是,可以将属性集分组为一个样式,该样式始终应用到一个或多个视图。However, sets of properties can be grouped into one style that is consistently applied to one or many views. 这可以提高代码的可读性,并使设计更改更易于实现。This can increase readability of code and make design changes easier to implement. 有关详细信息,请参阅样式For more information, see Styles.