John Livermore
John Livermore

Reputation: 31343

Equal sized labels in Xamarin Forms

With a horizontal StackLayout, I want to display 3 labels equal width across the screen. I don't want to use a WidthRequest property, but, rather, I want each label to be the same size with the content centered in the "box". And I want the labels to resize according to the device they are running on. So 3 labels, equal width, no matter the device.

I know this can be done with a Grid (Width="Auto"), but is it possible with a horizontally aligned StackLayout?

I was thinking this would work...

<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
    <Label Text="aaaa" 
            HorizontalOptions="FillAndExpand" 
            HorizontalTextAlignment="Center" 
            BackgroundColor="Blue" />
    <Label Text="aaaaaaaaaaaa" 
            HorizontalOptions="FillAndExpand" 
            HorizontalTextAlignment="Center" 
            BackgroundColor="Green" />
    <Label Text="aa" 
            HorizontalOptions="FillAndExpand" 
            HorizontalTextAlignment="Center"  
            BackgroundColor="Red" />
</StackLayout>

But it just resulted in this...

enter image description here

Upvotes: 2

Views: 645

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

Cause: When you add labels in stackLayout ,stackLayout will not make the subviews fit the size.

Solution:

Put the labels in a Grid. Refer the following code.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Label  Grid.Row="0" Grid.Column="0"  Text="aaaa" BackgroundColor="Blue" />
    <Label  Grid.Row="0" Grid.Column="1"  Text="aaaaaaaaaaaa" BackgroundColor="Green"/>
    <Label  Grid.Row="0" Grid.Column="2"  Text="aa"  BackgroundColor="Red" />

</Grid>

Upvotes: 7

Related Questions