Al John
Al John

Reputation: 900

InvalidCastException when using <Span> to format label text in MAUI

Can I make the <Span/> elements inherit styles from parent <Label/> or freely apply styles in some way?

I've been trying to use <Span/> elements to format <Label.FormattedText/> and I keep getting an InvalidCastException, unless I meet some very specific conditions that I am not familiar with. By default, the <Span/> elements are unstyled and they don't inherit from the parent <Label/>, so I have to completely style those to match all the other label texts in my app.

For example, I cannot use the Style attribute, FontFamily attribute or TextColor attribute for any <Span/> element at all without getting the InvalidCastException notifying that the "Object must implement IConvertible".

For this project I'm trying to have a simple label where one single word is bold and the rest is not:

<Label LineBreakMode="WordWrap">
    <Label.FormattedText>
        <FormattedString>
            <Span Text="Some placeholder text for"/>
            <Span Text=" this specific " FontAttributes="Bold"/>
            <Span Text="issue on StackOverflow"/>
        </FormattedString>
    </Label.FormattedText>
</Label>

This example works, but as soon as I apply the Style="{StaticResource SpanFormat}" to have the style below applied, I'm getting the InvalidCastException mentioned. The same for TextColor and FontFamily like mentioned.

<Style TargetType="Span" x:Key="SpanFormat">
    <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource PrimaryDark}}" />
    <Setter Property="BackgroundColor" Value="Transparent" />
    <Setter Property="FontFamily" Value="PTSansRegular" />
    <Setter Property="FontSize" Value="16" />
</Style>

Upvotes: 0

Views: 59

Answers (0)

Related Questions