Welsh King
Welsh King

Reputation: 3238

Stack Layout layout nightmare with Xamarin XAML forms

I have the following code:

  <StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" Margin="0,10,0,10" BackgroundColor="Green" Padding="5,5,5,5">
        <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" Margin="0,0,0,0" BackgroundColor="Blue">
              <Label Text="SHOW COMPLETED TASKS" BackgroundColor="Red" Style="{StaticResource lblSubHeading_Black}" />
        </StackLayout>
        <Switch x:Name="CompletedJobsSwitch" Toggled="CompletedJobsSwitch_Toggled" HorizontalOptions="EndAndExpand" IsToggled="{Binding isOn}" BackgroundColor="Yellow"/>
  </StackLayout>

It all loads fine but when the app loads it is showing, but the Switch is not flush right. Why? It's really annoying, seems really inconsistententer image description here I've looked at http://forums.xamarin.com/discussion/21226/how-to-right-align-a-view-inside-a-list-item but this doesn't work for me.

Any ideas?

Upvotes: 4

Views: 4633

Answers (3)

Mike_p
Mike_p

Reputation: 11

Maybe I'm just too late to the party and some bugs have been fixed, but for others that arrive here through searching:

For the lefthand item use HorizontalOptions="StartAndExpand"
For the right align item use HorizontalOptions="End"
The switch is a fixed length component, so you don't want to use expand.If you do use EndAndExpand, it will add some padding to the right, ruining your right alignment.
The label wants to fill the remaining space, so tell it to expand.

 <StackLayout VerticalOptions="Start" Orientation="Horizontal" Margin="0,10,0,10" BackgroundColor="Green" Padding="5,5,5,5">
            <Label Text="SHOW COMPLETED TASKS" BackgroundColor="Red"  HorizontalOptions="StartAndExpand"  />
            <Switch x:Name="CompletedJobsSwitch"  HorizontalOptions="End" IsToggled="false" BackgroundColor="Yellow"/>
</StackLayout>

Upvotes: 1

Mikalai Daronin
Mikalai Daronin

Reputation: 8716

This is well-known issue with combination of StackLayout and Label:

You could use workaround described by JamesMontemagno. The point is to use Grid instead of StackLayout in that case.

Upvotes: 4

Ive
Ive

Reputation: 1331

Use this

<Grid BackgroundColor="Green">
  <Grid.RowDefinitions>
    <RowDefinition Height="auto" />
  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="auto" />
  </Grid.ColumnDefinitions>
  <Label Text="SHOW COMPLETED TASKS" BackgroundColor="Red" />
  <Switch x:Name="CompletedJobsSwitch" BackgroundColor="Yellow" Grid.Column="1" />
</Grid>

Upvotes: 10

Related Questions