Александр
Александр

Reputation: 299

Horizontal alignment for ListView items

I have the page:

public partial class MenuPage : ContentPage
{
    public MenuPage ()
    {

        StackLayout menu = new StackLayout { };
        menu.Children.Add(new ListView
        {
            HorizontalOptions = LayoutOptions.Center,
            ItemsSource = new string[]
            {
                "Settings",
                "About"
            }
        });

        Content = menu;

    }
}

I'm trying to align by center the content of ListView items (with HorizontalOptions = LayoutOptions.Center), but the option has no effect (whatever values I set for HorizontalOptions - I will reach alignment just to the left side). How to center the contents of cells correctly?

Upvotes: 0

Views: 481

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

As Jason said , you need to set the HorizontalOptions of each items in ListView . It is easier to define it in xaml .If you do want to implement it in code behind , you could check the following code .

You could define a custom cell

public CustomCell()
{
   //instantiate each of our views

   StackLayout horizontalLayout = new StackLayout() {

      HorizontalOptions=LayoutOptions.CenterAndExpand,
      VerticalOptions = LayoutOptions.CenterAndExpand


   };

   Label Content = new Label();

   //set bindings

   Content.SetBinding(Label.TextProperty, ".");

   Content.HorizontalOptions = LayoutOptions.CenterAndExpand;
   Content.TextColor = Color.Red;

   horizontalLayout.Children.Add(Content);
   View = horizontalLayout;
}
StackLayout menu = new StackLayout { };

var listview = new ListView
{

   ItemsSource = new string[]
   {
      "Settings",
      "About"
   }
};

listview.ItemTemplate = new DataTemplate(typeof(CustomCell));

menu.Children.Add(listview);

Content = menu;

enter image description here

Upvotes: 1

Related Questions