Saftpresse99
Saftpresse99

Reputation: 979

Center content if text becomes bigger

i have this sample xaml:

<StackLayout Orientation="Horizontal"
             HorizontalOptions="CenterAndExpand">
  <StackLayout BackgroundColor="LightBlue">
    <Label Text="ABC"
           HorizontalTextAlignment="Center" />
    <Label Text="L"
           HorizontalTextAlignment="Center"></Label>
  </StackLayout>
  <BoxView BackgroundColor="Red" />
  <StackLayout BackgroundColor="LightGreen">
    <Label Text="ABC"
           HorizontalTextAlignment="Center" />
    <Label Text="C"
           HorizontalTextAlignment="Center"></Label>
  </StackLayout>
</StackLayout>

which produces this output:
Center ok
But if one of the four lables becomes bigger there are not centered anymore:
Bigger label

My goal is the following layout, which depends on the biggest label:
Center

I'm a beginner. So i hope somebody could help me with the correct layout.
Thanks

Upvotes: 1

Views: 30

Answers (1)

Mihail Duchev
Mihail Duchev

Reputation: 4821

StackLayout really isn't the best choice here, because it occupies the size dynamically (i.e. depending on its content). What's the better approach here is to use Xamarin.Forms' Grid layout.

This way, you can have a grid with 3 columns. Then, you will set your ColumnDefinitions's width to star (*). Like you can see in the Rows and columns section, setting the column's width to star means that:

Star – leftover row height or column width is allocated proportionally (a number followed by * in XAML).

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <StackLayout Grid.Column="0" /> <!-- Blue StackLayout wrapper -->
    <BoxView Grid.Column="1" /> <!-- Red BoxView -->
    <StackLayout Grid.Column="2" /> <!-- Green StackLayout wrapper -->
</Grid>

Basically, you will have divided the whole screen width to 3 equal parts, each resulting in an 33,3(3) % of the screen. Then, you can align the elements in the container as you wish.

Upvotes: 1

Related Questions