ぴーさんログ

だいたいXamarin.Formsのブログ

Xamarin.FormsでTextBlockのような事をする

テキストの一部だけ色やフォントサイズを変えたい時、WPFならTextBlockを使いますね? Xamarin.Formsでは Label.FormattedText で実現できます。

サンプル

XAMLで書くとこんな感じ

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span Text="名前:" ForegroundColor="Gray"/>
            <Span Text="あべなな" FontSize="Large" ForegroundColor="Maroon"/>
            <Span Text=" さん"/>
            <Span Text="{x:Static x:Environment.NewLine}" />
            <Span Text="年齢:"  ForegroundColor="Gray"/>
            <Span Text="17" FontSize="Large" FontAttributes="Bold" ForegroundColor="Maroon"/>
            <Span Text="歳" />
        </FormattedString>
    </Label.FormattedText>
</Label>

結果はこんな感じ

f:id:ticktack623:20160211175321j:plain

C#で書くとこんな感じ

new Label {
    FormattedText = new FormattedString {
        Spans = {
            new Span {
                Text = "名前:",
                ForegroundColor = Color.Gray },
            new Span {
                Text = "あべなな",
                FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
                ForegroundColor = Color.Maroon },
            new Span { Text = " さん" },
            new Span { Text = System.Environment.NewLine },
            new Span {
                Text = "年齢:",
                ForegroundColor = Color.Gray },
            new Span {
                Text = "17",
                FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
                FontAttributes = FontAttributes.Bold,
                ForegroundColor = Color.Maroon },
            new Span { Text = " 歳" },
        },
    },
};

残念な点

SpanクラスはBindableObjectではないのでBindningが使えません。のでUserVoiceに投票して待ちましょう。 あるいはサンプルに書いたようにStatic Propertyで何とかするぐらいでしょうか。

Extend Span with bindable Text and TapGesture – Customer Feedback for Xamarin Platform

Unseal Span or Make it Bindable – Customer Feedback for Xamarin Platform