2
votes

I'm trying to create a view that has several controls centered inside a StackLayout. When I have just one like this:

<StackLayout Orientation="Vertical" HorizontalOptions="Center" >
    <controls:BindablePicker />
</StackLayout>

It works fine: Centered

However, when I try to add a ListView, e.g.:

<StackLayout Orientation="Vertical" HorizontalOptions="Center" >
  <controls:BindablePicker />
  <ListView HorizontalOptions="Center" >
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <ViewCell.View>
            <StackLayout Orientation="Horizontal">
              <controls:BindablePicker Title="Length" />
              <controls:BindablePicker Title="Units" />
            </StackLayout>
          </ViewCell.View>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</StackLayout>

Everything is left justified and takes up the entire screen: Left justified

I'd like the widths of all controls to be as short as possible centered on the screen. Right now I'm using a ListView because I'm binding a list of objects and I thought that would be easier than trying to use a Grid.

Any suggestions would be greatly appreciated. Thanks.

UPDATE I updated my ViewCell to replace the StackLayout with a Grid, then put the ListView inside a grid as follows:

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="2*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <ListView Grid.Row="0" Grid.Column="1" HorizontalOptions="Center" SeparatorVisibility="None">

This is pretty much what I want, except the top picker is taking up the entire width of the screen, instead of being only as wide as it needs to be and centered.

1

1 Answers

3
votes

There is one small difference between your first StackLayout example and the second StackLayout example (the example inside of the ViewCell), and this is causing the trouble you're experiencing:

  • The first StackLayout example is Orientation="Vertical"
  • The second StackLayout example (the example inside of your ViewCell) is Orientation="Horizontal"

StackLayouts in Xamarin.Forms only honor the HorizontalOptions property when Orientation="Vertical", and only honor the VerticalOptions property when Orientation="Horizontal".

This "feature" of StackLayouts is not well documented, and I couldn't find an example link that specifies it. Personally, I learned this fact from an instructor during a Xamarin University class.

To center the controls of the ViewCell, use a Grid layout instead of a StackLayout. Here's An example:

http://www.trsneed.com/customize-xamarin-forms-listview-with-viewcell/