Xamarin.Forms ラベル

サンプルのダウンロードサンプルのダウンロード

でテキストを表示する Xamarin.Forms

ビューは Label 、単一行と複数行の両方のテキストを表示するために使用されます。 ラベルには、テキストの装飾、色付きのテキストを含め、カスタム フォント (ファミリ、サイズ、オプション) を使用できます。

テキストの装飾

下線と取り消し線のテキスト装飾は、 プロパティを Label 1 つ以上TextDecorationsLabel.TextDecorations列挙メンバーに設定することで、インスタンスに適用できます。

  • None
  • Underline
  • Strikethrough

次の XAML の例では、 プロパティの設定を Label.TextDecorations 示します。

<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# コードを次に示します。

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

次のスクリーンショットは、インスタンスに適用される TextDecorations 列挙メンバーを Label 示しています。

テキスト装飾を含むラベル

注意

テキスト装飾は、インスタンスにも Span 適用できます。 クラスの Span 詳細については、「 書式設定されたテキスト」を参照してください。

テキストの変換

では Label 、 プロパティに格納されているテキストの大文字と小文字を Text 変換するには、 プロパティを TextTransform 列挙の値に TextTransform 設定します。 この列挙には、次の 4 つの値があります。

  • None は、テキストが変換されていないことを示します。
  • Default は、プラットフォームの既定の動作が使用されることを示します。 これは、TextTransform プロパティの既定値です。
  • Lowercase は、テキストが小文字に変換されることを示します。
  • Uppercase は、テキストが大文字に変換されることを示します。

次の例は、テキストを大文字に変換する方法を示しています。

<Label Text="This text will be displayed in uppercase."
       TextTransform="Uppercase" />

これに相当する C# コードを次に示します。

Label label = new Label
{
    Text = "This text will be displayed in uppercase.",
    TextTransform = TextTransform.Uppercase
};

文字間隔

プロパティを値に設定することで、インスタンスにLabelLabel.CharacterSpacing文字間隔をdouble適用できます。

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

これに相当する C# コードを次に示します。

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

結果として、 によって Label 表示されるテキスト内の文字は、デバイスに依存しない単位が離れた間隔 CharacterSpacing になります。

改行

XAML から、 内のテキストを新しい行にLabel強制的に追加するための 2 つのメイン手法があります。

  1. Unicode 改行文字 ("&#10;") を使用します。
  2. プロパティ要素の構文を使用してテキストを指定します。

次のコードは、両方の手法の例を示しています。

<!-- Unicode line feed character -->
<Label Text="First line &#10; Second line" />

<!-- Property element syntax -->
<Label>
    <Label.Text>
        First line
        Second line
    </Label.Text>
</Label>

C# では、"\n" 文字を使用してテキストを強制的に改行できます。

Label label = new Label { Text = "First line\nSecond line" };

バインド可能な TextColor プロパティを使用して、カスタム テキストの色を使用するようにラベルを設定できます。

各プラットフォームで色を使用できるようにするには、特別な注意が必要です。 各プラットフォームにはテキストと背景色の既定値が異なるため、それぞれで動作する既定値を選択するように注意する必要があります。

次の XAML の例では、 のテキストの色を 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# コードを次に示します。

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 示しています。

Label TextColor の例

色の詳細については、「 」を参照してください。

フォント

Labelフォントを指定する方法の詳細については、「 フォント」を参照してください。

切り捨てと折り返し

ラベルは、 プロパティによって公開される複数の方法のいずれかで、1 行に収まらないテキストを LineBreakMode 処理するように設定できます。 LineBreakMode は、次の値を持つ列挙体です。

  • HeadTruncation – テキストの先頭が切り捨てられ、末尾が表示されます。
  • CharacterWrap – 文字境界の新しい行にテキストを折り返します。
  • MiddleTruncation – テキストの先頭と末尾が表示され、中央は省略記号で置き換えられます。
  • NoWrap – テキストは折り返されず、1 行に収まる限り多くのテキストのみが表示されます。
  • TailTruncation – テキストの先頭を示し、末尾を切り捨てます。
  • WordWrap – 単語の境界でテキストを折り返します。

特定の行数を表示する

によって表示されるLabel行数は、 プロパティを値にLabel.MaxLinesint設定することで指定できます。

  • が -1 (既定値) の場合 MaxLinesLabel は、プロパティの LineBreakMode 値を考慮して、1 行のみ表示するか、切り捨てられたか、すべてのテキストを含むすべての行を表示します。
  • が 0 の場合 MaxLinesLabel は表示されません。
  • が 1 の場合MaxLines、結果は プロパティを LineBreakMode 、、HeadTruncationMiddleTruncationまたは TailTruncationに設定したNoWrap場合と同じです。 ただし、 Label は省略記号の LineBreakMode 配置に関して プロパティの値を考慮します (該当する場合)。
  • が 1 より大きい場合 MaxLinesLabel は、省略記号の配置に関して プロパティの LineBreakMode 値を考慮しながら、指定された行数まで表示されます (該当する場合)。 ただし、 プロパティを MaxLines 1 より大きい値に設定しても、 プロパティが にNoWrap設定されている場合LineBreakModeは効果はありません。

次の XAML の例では、 に プロパティを MaxLines 設定する方法を 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# コードを次に示します。

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

次のスクリーンショットは、テキストが 2 行を超える長さの場合に プロパティを 2 に設定 MaxLines した結果を示しています。

ラベルの MaxLines の例

HTML を表示する

Labelクラスには プロパティがありTextType、インスタンスでプレーン テキストと HTML テキストのどちらをLabel表示するかを決定します。 このプロパティは、列挙体のメンバーのいずれかに設定する TextType 必要があります。

  • Text は、 に Label プレーン テキストが表示されることを示し、 が プロパティの Label.TextType 既定値です。
  • Html は、 に HTML テキストが表示されることを Label 示します。

そのため、Labelインスタンスは、 プロパティを にHtml設定し、 プロパティを Label.TextTypeLabel.Text HTML 文字列に設定することで HTML を表示できます。

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

上記の例では、 記号を使用して HTML の二重引用符文字を \ エスケープする必要があります。

XAML では、 と > のシンボルをさらにエスケープするため、HTML 文字列が<読み取れなくなる可能性があります。

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

また、読みやすくするために、HTML をセクションに CDATA インライン化することもできます。

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

この例では、 Label.Text プロパティは セクションでインライン化された HTML 文字列に CDATA 設定されています。 これは、 プロパティが ContentProperty クラスの Text であるためにLabel機能します。

次のスクリーンショットは、表示されている Label HTML を示しています。

iOS と Android の HTML を表示するラベルのスクリーンショット

重要

での HTML の Label 表示は、基になるプラットフォームでサポートされている HTML タグに限定されます。

書式付きテキスト

ラベルは、 FormattedText 同じビューで複数のフォントと色を持つテキストを表示できるプロパティを公開します。

プロパティはFormattedText、 プロパティを介してSpans設定された 1 つ以上Spanのインスタンスで構成される 型FormattedStringです。 次 Span のプロパティを使用して、視覚的な外観を設定できます。

  • BackgroundColor – スパンの背景の色。
  • CharacterSpacing: double 型、Span テキストの文字間の間隔。
  • Font – スパン内のテキストのフォント。
  • FontAttributes – スパン内のテキストのフォント属性。
  • FontFamily – スパン内のテキストのフォントが属するフォント ファミリ。
  • FontSize – スパン内のテキストのフォントのサイズ。
  • ForegroundColor – スパン内のテキストの色。 このプロパティは古く、プロパティに TextColor 置き換えられました。
  • LineHeight - スパンの既定の線の高さに適用する乗数。 詳細については、「線の 高さ」を参照してください。
  • Style – スパンに適用するスタイル。
  • Text – スパンのテキスト。
  • TextColor – スパン内のテキストの色。
  • TextDecorations - スパン内のテキストに適用する装飾。 詳細については、「 テキスト装飾」を参照してください。

BackgroundColorText、およびTextバインド可能なプロパティの既定のOneWayバインド モードは です。 このバインド モードの詳細については、「バインド モード」ガイド の「既定バインド モード 」を参照してください。

さらに、 プロパティを GestureRecognizers 使用して、 のジェスチャに応答するジェスチャ認識エンジンのコレクションを Span定義できます。

注意

で HTML Spanを表示することはできません。

次の XAML の例では、 FormattedText 3 つの Span インスタンスで構成される プロパティを示します。

<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# コードを次に示します。

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

重要

Span プロパティはText、データ バインディングを使用して設定できます。 詳細については、データ バインディングに関するページを参照してください。

Spanは、スパンGestureRecognizersのコレクションに追加されるジェスチャにも応答できることに注意してください。 たとえば、上記の TapGestureRecognizer コード例の 2 つ目 Span に が追加されています。 したがって、これがSpanタップされると、 TapGestureRecognizer プロパティでCommand定義された をICommand実行して 応答します。 ジェスチャ認識エンジンの詳細については、「ジェスチャ」を参照してくださいXamarin.Forms

次のスクリーンショットは、 プロパティを 3 つのSpanインスタンスに設定したFormattedString結果を示しています。

Label FormattedText の例

[行間]

と のLabel垂直方向の高さは、 プロパティまたは Span.LineHeight を値にdouble設定Label.LineHeightすることでカスタマイズSpanできます。 iOS および Android では、これらの値は元の行の高さの乗数であり、ユニバーサル Windows プラットフォーム (UWP) Label.LineHeight では、プロパティ値はラベルのフォント サイズの乗数です。

注意

  • iOS では、 プロパティと Span.LineHeight プロパティをLabel.LineHeight使用すると、1 行に収まるテキストの行の高さと、複数の行に折り返されるテキストが変更されます。
  • Android では、 プロパティと Span.LineHeight プロパティはLabel.LineHeight、複数行に折り返されるテキストの行の高さのみを変更します。
  • UWP では、プロパティは Label.LineHeight 複数行に折り返されるテキストの行の高さを変更します Span.LineHeight 。プロパティは効果がありません。

次の XAML の例では、 に プロパティを LineHeight 設定する方法を 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# コードを次に示します。

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

次のスクリーンショットは、 プロパティを 1.8 に設定した Label.LineHeight 結果を示しています。

Label LineHeight の例

次の XAML の例では、 に プロパティを LineHeight 設定する方法を 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# コードを次に示します。

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

次のスクリーンショットは、 プロパティを 1.8 に設定した Span.LineHeight 結果を示しています。

Span LineHeight の例

パディング

Padding は要素とその子要素の間のスペースを表し、要素を独自のコンテンツから分離するために使用されます。 パディングは、 プロパティを値に Label 設定 Label.Padding することでインスタンスに Thickness 適用できます。

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

これに相当する C# コードを次に示します。

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 では、 プロパティを Label 設定 Padding する が作成されると、パディングが適用され、パディング値は後で更新できます。 ただし、 プロパティを Label 設定 Padding しない が作成された場合、後で設定しようとしても効果はありません。

Android とユニバーサル Windows プラットフォームでは、 Padding の作成時以降にプロパティ値をLabel指定できます。

パディングの詳細については、「 余白とパディング」を参照してください。

および Span インスタンスによってLabel表示されるテキストは、次の方法でハイパーリンクに変換できます。

  1. または の TextColor プロパティと TextDecoration プロパティを Label 設定 Spanします。
  2. TapGestureRecognizerプロパティが GestureRecognizers にバインドされCommandParameter、そのプロパティに開く ICommandURL が含まれている または CommandSpanのコレクションLabelに を追加します。
  3. ICommandによって実行される を定義しますTapGestureRecognizer
  4. によって実行されるコードを記述します ICommand

Hyperlink Demos サンプルから取得した次のコード例は、コンテンツが複数Spanのインスタンスから設定されている をLabel示しています。

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

この例では、1 番目と 3 番目 Span のインスタンスはテキストで構成され、2 番目 Span のインスタンスは適用可能なハイパーリンクを表します。 テキストの色は青に設定され、下線付きテキストの装飾が付きます。 これにより、次のスクリーンショットに示すように、ハイパーリンクの外観が作成されます。

ハイパーリンク ハイパーリンク

ハイパーリンクがタップされると、 TapGestureRecognizer はそのプロパティでCommand定義された をICommand実行して応答します。 さらに、 プロパティで CommandParameter 指定された URL は パラメーターとして に ICommand 渡されます。

XAML ページの分離コードには、次の実装が TapCommand 含まれています。

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 パラメーターとして渡します。 メソッドは Launcher.OpenAsync によって Xamarin.Essentials提供され、Web ブラウザーで URL を開きます。 したがって、全体的な効果は、ページ上でハイパーリンクがタップされると、Web ブラウザーが表示され、ハイパーリンクに関連付けられている URL に移動することです。

ハイパーリンクを作成する前の方法では、アプリケーションでハイパーリンクが必要になるたびに繰り返しコードを記述する必要があります。 ただし、 クラスと クラスのLabel両方をサブクラス化して クラスと HyperlinkSpan クラスを作成HyperlinkLabelし、ジェスチャ認識エンジンとテキスト書式設定コードを追加Spanできます。

Hyperlink Demos サンプルから取得した次のコード例は、 クラスをHyperlinkSpan示しています。

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、プロパティと関連付けられた BindablePropertyを定義Urlし、コンストラクターはハイパーリンクの外観と、TapGestureRecognizerハイパーリンクがタップされたときに応答する を設定します。 HyperlinkSpanがタップされると、 TapGestureRecognizer は メソッドをLauncher.OpenAsync実行して応答し、 プロパティでUrl指定された URL を Web ブラウザーで開きます。

クラスを HyperlinkSpan 使用するには、 クラスのインスタンスを 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://learn.microsoft.com/appcenter/" />
                    <Span Text=" to view AppCenter documentation." />
                </FormattedString>
            </Label.FormattedText>
        </Label>
    </StackLayout>
</ContentPage>

ラベルのスタイル設定

前のセクションでは、インスタンスごとに設定 LabelSpan プロパティについて説明しました。 ただし、プロパティのセットは、1 つまたは複数のビューに一貫して適用される 1 つのスタイルにグループ化できます。 これにより、コードの読みやすさが向上し、設計の変更を実装しやすくなります。 詳細については、「 スタイル」を参照してください。