4
votes

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?

3
It's not inconsistent. The StackLayout only takes as much space as needed. Try to put a Grid around it at the highest level. - Gerald Versluis
when I say inconstant, i mean XAML for Xamarin forms, but ive set the StackLayout tto fill and expand, why isnt it doing that ? Adding a grid seems to be sticking a plaster over the issue. - Welsh King
You don't have to add a grid, just replace your top-level StackLayout with a Grid. - Gerald Versluis

3 Answers

10
votes

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>
4
votes

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.

1
votes

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>