简体   繁体   中英

Text aligned with link button in Xamarin Forms

I'm working on an app where several times there are text labels combined with buttons or where a part of the text has a different color.

This time, I need to achieve this: 在此输入图像描述

The "Sign in" text button has to have an action attached to it and also have a different look from the rest of the text.

I have tried with a StackView with the Horizontal attribute but it just depends too much on the width of the device and text length and it doesn't look centered horizontally on the screen.

On Html I would do something like

Already have an account? <a>Sign in</a>

Is there something like that on XAML?

Yes - spans. You can build a formatted string using spans that have different fonts, colours, sizes etc.

<Label>
    <Label.FormattedText>
        <FormattedString>
            <FormattedString.Spans>
                <Span Text="Hello" ForegroundColor="Red" FontAttributes="Italic" FontSize="10" />
                <Span Text="World" ForegroundColor="Blue" FontSize="10" />
            </FormattedString.Spans>
        </FormattedString>
    </Label.FormattedText>
</Label>

Span text is not bindable, but FormattedText on Label is, so you can build a FormattedString in your view model and bind that to the FormattedText property.

A grid with auto-sized columns and a TapGestureRecognizer on the Sign In label is one approach that will produce a consistent look on iOS and Android as buttons are not used.

<Grid Padding="20">
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0" Grid.Column="0" Text="Already have an account?" TextColor="Black" BackgroundColor="White" />
    <Label x:Name="onSignIn" Grid.Row="0" Grid.Column="1" Text="Sign In" TextColor="Red" BackgroundColor="White" />
</Grid>

在此输入图像描述

In the code behind:

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (sender, e) => D.WriteLine("Tapped");
onSignIn.GestureRecognizers.Add(tapGestureRecognizer);

您也可以尝试这个现有的解决方案: https//theconfuzedsourcecode.wordpress.com/tag/xamarin-hyperlink-label/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM