mercredi 7 février 2018

ListView in Xamarin.Forms

We will summarize the controls (ListView) that is able to display lists in Xamarin.forms, we will explain some properties used.

How to use ListView

We will work in MainPage.xaml, we start by add this XAML code in MainPage.xaml as follows:
    <StackLayout>
            <ListView x:Name="MyListView"/>
    </StackLayout>

In MainPage.xaml.cs, we will add this C# code as follows:
   // iOS only, take a margin at the top
    this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);

   // Generate a ListView
    // Create a list of 100 lines "item-0 ~ item-99"
    this.MyListView.ItemsSource = Enumerable.Range(0, 100).Select(n => $"item-{n}");

And the result is:

Public property list of ListView

The number of properties of the ListView control is more than other controls, and there are things that are hard to understand so I will go out carefully. Also, unless otherwise noted in the code behind, I will write XAML after using the above.

Footer property

Gets or sets the string, binding, or view to be displayed at the bottom of the list view.

XAML:
    <StackLayout>
            <ListView x:Name="MyListView" Footer="This is Footer"/>
</StackLayout>
Result:

FooterTemplate property

Gets or sets the data template to use for formatting the data object displayed at the bottom of the list view.

If only the Footer property was set, only characters could be set. By using the FooterTemplate property you can change the way the footer is expressed.

XAML:
 <ListView x:Name="MyListView"
                  Footer="This is Footer">
                <ListView.FooterTemplate>
                    <DataTemplate>
                        <Label Text="{Binding}"
                           FontSize="30"/>
                    </DataTemplate>
                </ListView.FooterTemplate>
  </ListView>
Result:

GroupDisplayBinding Property · IsGroupingEnabled Property

Gets or sets the binding used to display the group header.
You can group in the list by using the GroupDisplayBinding property, At the same time, I will set the IsGroupingEnabled property to True.
XAML in MainPage.xaml

   <ListView x:Name="MyListView"
                      IsGroupingEnabled="True"
                      GroupDisplayBinding="{Binding SectionLabel}" />

C# Code-Behind in MainPage.xaml.cs

public class GroupingItem : ObservableCollection<string>
    {
        public string SectionLabel { get; set; }
    }

    readonly ObservableCollection<GroupingItem> _items = new ObservableCollection<GroupingItem>();

        public MainPage()
{
InitializeComponent();

            // iOS only, take a margin at the top
    this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);

            // Generate a ListView
            // Create a list of 100 lines "item-0 ~ item-99"
    this.MyListView.ItemsSource = Enumerable.Range(0, 100).Select(n => $"item-{n}");

            //Participants section created
            var item = new GroupingItem
    {
        SectionLabel = "Participants",
    };

            //Add each name to a section of a Participants
            item.Add("Hamida REBAI");
    item.Add("Rayen Trabelsi");
    item.Add("Mohamed trabelsi");
    _items.Add(item);

            //Topics section created
            item = new GroupingItem
    {
        SectionLabel = "Topics",
    };

            //Add a name to a Topic's section
    item.Add("ASP.NET Core 2.0");
    item.Add("Learning Cloud in Azure");
    item.Add("Introduce XAMARIN");
    _items.Add(item);

            //Set grouping item to ItemsSource of ListView
    MyListView.ItemsSource = _items;


        }

Result:

GroupHeaderTemplate property

Gets or sets the DataTemplete of the group header.
The GroupDisplayBinding property could only represent the text of the header.
By using the GroupHeaderTemplate property you can change the representation of the value.
As a rule of how it feels the same as the FooterTemplate property.
Result:



MainPage.xaml.cs is the same as the GroupDisplayBinding property part.

GroupShortNameBinding property

Gets or sets the binding of the name displayed in the grouped jump list.
The GroupShortNameBinding property can only be used on iOS. I can display what is grouping on the right side of the screen.
XAML:
    <ListView x:Name="MyListView"
                      IsGroupingEnabled="True"
                      GroupShortNameBinding ="{Binding SectionLabel}" />
Result in Android but it's different in iOS


HasUnevenRows property

Gets or sets a Boolean value that indicates whether this ListView element has nonuniform rows.
HasUnevenRows property is a property that makes the height of list view non-uniform. The height is automatically set according to the contents of the list view.
XAML:
     <ListView x:Name="MyListView"  HasUnevenRows="true"/>
And C# Code-Behind
InitializeComponent();

            // iOS only, take a margin at the top
    this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);

    this.MyListView.ItemsSource = new List<string>
    {
                "Xamarin Forms is based on the XAML / WPF model" ,
                "MVVM divides an application into three layers:",
                "The Model provides underlying data, sometimes involving file or web accesses.",
                "The ViewModel connects the Model and the View.",
                "It helps to manage the data" ,
                "The View is the user interface or presentation layer, generally implemented in XAML."

            };
Result:

It seems that it is not reflected if it is only letters...
You can change the size of the cell dynamically. Android has been dynamically resized originally, but if Cell.ForceUpdateSize() you call it with this change, the size will be updated.

"Depending on the platform, the cost of treatment is high", in fact, it is slow to follow the update of the size when used on iOS.
Example:
Create a custom ViewCell for confirmation, the height of BoxView will change according to the slider. By calling Cell.ForceUpdateSize () according to the MeasureInvalidated event of the StackLayout root element, the cell size of the ListView is updated.
C# Code:
We will add a new Class named: MyViewCell that Inherit from ViewCell:
 public class MyViewCell : ViewCell
    {
        public MyViewCell()
        {
            var label = new Label();
            label.SetBinding(Label.TextProperty,
                ".", BindingMode.OneWay);

            var slider = new Slider
            {
                Maximum = 100,
                Minimum = 0,
                Value = 50,
            };

            var boxView = new BoxView
            {
                Color = Color.Blue,
                BindingContext = slider,
            };
            boxView.SetBinding(VisualElement.HeightRequestProperty,
                "Value", BindingMode.OneWay);

            var stackLayout = new StackLayout
            {
                Children = {
                    label,
                    slider,
                    boxView,
                },
            };

            // Here, Cell size of ListView is updated
            stackLayout.MeasureInvalidated +=
                (sender, e) => ForceUpdateSize();

            View = stackLayout;
        }
    }

In MainPage.xaml.cs we will write this code C#:
InitializeComponent();

            // iOS only, take a margin at the top
    this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
                    this.MyListView.HasUnevenRows = true;
    this.MyListView.ItemsSource = new[] {1, 2, 3, 4, 5, 6,};
    this.MyListView.ItemTemplate = new DataTemplate(typeof(MyViewCell));

And the result will be this:

Header property

Gets or sets a string, binding, or view to be displayed at the top of the list view.
It is a property that you can set the header. It is the same as footer as a lick of usage.
XAML:
 <StackLayout>
            <ListView x:Name="MyListView"   HasUnevenRows="true" Header="This is my Header!"/>

 </StackLayout>
C# Code Behind:
We keep a previous sample:
 this.MyListView.ItemsSource = Enumerable.Range(0, 100).Select(n => $"item-{n}");
Result:

HeaderTemplate property

Gets or sets the data template to use for formatting the data object displayed at the top of the list view.
I can change the expression of the header. As a way to use it together with the FooterTemplate property.
XAML:

 <StackLayout>
            <ListView x:Name="MyListView"   HasUnevenRows="true" Header="This is my Header!">
                <ListView.HeaderTemplate>
                    <DataTemplate>
                        <Label Text="{Binding}" FontSize="30"></Label>
                    </DataTemplate>
                </ListView.HeaderTemplate>
            </ListView>

  </StackLayout>
Same C# Code-Behind of the previous example.

IsPullToRefreshEnabled property

Gets or sets a value that indicates whether the user should swipe and update the application.

The default is false.
IsPullToRefreshEnabled property is set to whether to pull an update.
I will pull it and update it and write a program that stops updating after 2 seconds.


IsRefreshing property

Gets or sets a value indicating whether the list view is currently being updated.
The IsRefreshing property allows you to set whether the update is complete. 

RefreshCommand property

Gets or sets the command to be executed when the list view is updated.

XAML:

            <ListView x:Name="MyListView"
                      IsPullToRefreshEnabled="True"
                      Refreshing="MyListView_OnRefreshing" />

C# Code-Behind
We keep the same ItemSource but we will add a new Method
 private async void MyListView_OnRefreshing(object sender, EventArgs e)
    {
        //Wait for 4 seconds processing
        await Task.Delay(4000);

        //Stop refreshing
        this.MyListView.IsRefreshing = false;

        }
Result:


RowHeight property

Gets or sets the value representing the height of the line.
The RowHeight property is a property that allows you to set the height of an item.
XAML:
  <ListView x:Name="MyListView"

                   RowHeight="150" />
Result:

SelectedItem Property

Gets or sets the currently selected item from ListView.ItemsSource.
In the SelectedItem property, you can set the items to select. Here I will let you select item - 5.
XAML:
   <ListView x:Name="MyListView"

                      SelectedItem="item-5" />
Or we can force the selection in the CodeBehind part:

 MyListView.SelectedItem = "item-5";

Result:

SeparatorColor Property

Gets or sets the color of the bar separating the list items.
In the SeparatorColor property, you can change the color of the separator line for each item. I will change it to Blue here.
XAML:
 <ListView x:Name="MyListView" SeparatorColor="Blue" />

SeparatorVisibility property

Gets or sets a value indicating whether a separator is displayed between items.
Possible values are Default · None, initial value is Default.
In the SeparatorVisibility property, you can set whether or not to show separator lines for each item. Here I will set None and try clearing the separator line.
XAML:
<ListView x:Name="MyListView" SeparatorVisibility="None" />
Result:


Public Event List of ListView

In this part I will summarize the ListView's event method.

ItemAppearing event 

An event that fires when the visual representation of an item is added to the visual layout.
XAML:
  <!--ListView-->
            <ListView x:Name="MyListView" 
                      ItemsSource="{Binding Mode=TwoWay}"
                      ItemAppearing="MyListView_OnItemAppearing" />

            <!-- Add new element -->
            <Button x:Name="AddNameBtn"
                    Text="ListView Add Item"
                    FontSize="20"
                    Clicked="AddNameBtn_OnClicked"  />
            <!-- Delete all elements -->
            <Button x:Name="DeleteNameBtn"
                    Text="ListView delete all Items"
                    FontSize="20"
                    Clicked="DeleteNameBtn_OnClicked"/>


C# CodeBehind

    public List<string> ItemSource { get; set; } = Enumerable.Range(1, 5)
        .Select((x, index) => $"{index}- Element")
        .ToList();

  public MainPage()
{
InitializeComponent();

            // iOS only, take a margin at the top
            this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
    MyListView.ItemsSource = ItemSource;
}
    private void AddNameBtn_OnClicked(object sender, EventArgs e)
    {
        //Add item
            this.ItemSource.Add($"{this.ItemSource.Count}-  Element");

        //Once you have to empty the ListView
            MyListView.ItemsSource = null;

            //ItemsSource in ListView
            MyListView.ItemsSource = ItemSource;
        }

    private void DeleteNameBtn_OnClicked(object sender, EventArgs e)
    {
        this.ItemSource.RemoveAll(x => true);
        MyListView.ItemsSource = null;
        }

    private void MyListView_OnItemAppearing(object sender, ItemVisibilityEventArgs e)
    {
        //throw new NotImplementedException();
    }
Result
If we click on "ListView delete all Items" Button, we delete all elements.

If we click on "ListView Add Item" Button, we add a new element as shown: 6- Element




As you can see by following step execution, it seems that the ItemAppearing event is firing for each item at the timing of actual drawing, not at the timing added to the ItemsSource property. So in this program, five ItemAppearing events are firing.

ItemDisappearing event

This event fires when the visual representation of the item is deleted from the visual layout.
Likewise, the ItemDisappearing event fires for the number of deleted items.
In XAML

 <ListView x:Name="MyListView" 
                      ItemsSource="{Binding Mode=TwoWay}"
                      ItemAppearing="MyListView_OnItemAppearing" 
                      ItemDisappearing="MyListView_OnItemDisappearing"/>

C# CodeBehind
  private void MyListView_OnItemDisappearing(object sender, ItemVisibilityEventArgs e)
    {
        
    }

ItemSelected event

It is an event that fires when an item is selected.
The ItemSelected event fires when an item of the ListView control is selected.
XAML:
 <ListView x:Name="MyListView"
                      ItemSelected="MyListView_OnItemSelected"
                    />

            <Label x:Name="LblSelected"
                   FontSize="50"/>

in C# CodeBehind
  public List<string> ItemSource { get; set; } = Enumerable.Range(1, 5)
        .Select((x, index) => $"{index}- Element")
        .ToList();

        public MainPage()
{
InitializeComponent();

            // iOS only, take a margin at the top
            this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
    MyListView.ItemsSource = ItemSource;
}
    private void MyListView_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        this.LblSelected.Text = e.SelectedItem.ToString();

        }
Result :

You can see it by stepping through the above code, but the ItemTapped event fires after the ItemSelected event fires.

ItemTapped event

It is an event that fires when an item is tapped.
The ItemSelected event is not fired when the same item as the previous item is selected, but the ItemTapped event will fire when the item is tapped.
For the ItemTapped event, we have Group information. I attempted to give an example using this information, but since I could not use it well, I will skip it here.

XAML
   <ListView x:Name="MyListView"
                      ItemSelected="MyListView_OnItemSelected"
                      ItemTapped="MyListView_OnItemTapped"
                    />
C# CodeBehind Event:
  private void MyListView_OnItemTapped(object sender, ItemTappedEventArgs e)
    {
        this.LblSelected.Text = e.Item.ToString();
    }
Result:

Refreshing event

The event that fires when the list view is updated.
The Refreshing event is an event that will fire when refreshing ~. It is good to use IsPullToRefreshEnabled property and IsRefreshing property when refreshing.

IsPullToRefreshEnabled property is set to whether to pull and update. The IsRefreshing property allows you to set whether the update is complete ~. I will pull it and update it and write a program that stops updating after 2 seconds.
See sample of sPullToRefreshEnabled property.

Public Method List of ListView

BeginRefresh () method

Set the ListView.IsRefreshing property to true and enter the refresh state.
XAML:
<ListView x:Name="MyListView" />

            <!--Make a refresh state-->
            <Button x:Name="RefreshBtn"
                    Text="Refresh State"
                    FontSize="20"
                    Clicked="RefreshBtn_OnClicked"/>
/>

In MainPage.xaml.cs CodeBehind
  private void RefreshBtn_OnClicked(object sender, EventArgs e)
    {
        MyListView.BeginRefresh();
    }

  
We have the same example and the result is:

EndRefresh () method

Set the ListView.IsRefreshing property to false and end the refresh state.
<ListView x:Name="MyListView" />

            <!--Make a refresh state-->
            <Button x:Name="RefreshBtn"
                    Text="Refresh State"
                    FontSize="20"
                    Clicked="RefreshBtn_OnClicked"/>

            <!-- Button to stop fresh state-->
            <Button x:Name="StopRefreshBtn"
                    Text="Stop Refresh"
                    FontSize="20"
                    Clicked="StopRefreshBtn_OnClicked"/>
And the C# Code Behind:

  private void StopRefreshBtn_OnClicked(object sender, EventArgs e)
    {
        MyListView.EndRefresh();
           }

ScrollTo (Object, ScrollToPosition, Boolean) Method

Scroll the ListView to the item.
The method ScrollTo (Object, ScrollToPosition, Boolean) is a method that scrolls to the specified item. You can set which item to scroll (first argument), where to scroll (second argument), scroll using animation (third argument).
XAML:
   <ListView x:Name="MyListView" />
            <Picker x:Name="Picker"
                    SelectedIndexChanged="Picker_OnSelectedIndexChanged"/>

And in the code Behind:
  public List<string> ItemSource { get; set; } = Enumerable.Range(1, 100)
        .Select((x, index) => $"{index}- Item")
        .ToList();

        public MainPage()
{
InitializeComponent();

            // iOS only, take a margin at the top
            this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
    MyListView.ItemsSource = ItemSource;

    for (var i = 0; i < 100; ++i)
    {
        Picker.Items.Add($"{i} Item");
    }
}
   private void Picker_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        var selectedItem = Picker.Items[Picker.SelectedIndex];
        MyListView.ScrollTo(selectedItem, ScrollToPosition.Center, true);
        }
Result:
If we select "40 Item" we will be scrolled in the ListView to the row containing the same value.

ArgumentDescription
First argument (Object)Set which item to scroll
Second argument (ScrollToPosition)Set where to position after scrolling
Possible settings are as follows
-Center: Scrolls and displays the specified item in the center of the screen.
- End: Items scrolled and specified will be displayed at the bottom of the screen.
- MakeVisible: Scroll to display the specified list item.
- Start: Scrolls the specified item on the screen.
Third argument (Boolean)Set whether to use animation when scrolling.

ScrollTo (Object, Object, ScrollToPosition, Boolean) Method

Scrolls the ListView to items in the group.
* Even if this code is executed, the intended result cannot be obtained.
In the ScrollTo (Object, Object, ScrollToPosition, Boolean) method, one argument is added, and you can specify a group.
XAML:
          <ListView x:Name="MyListView"
                      IsGroupingEnabled="True"
                      GroupDisplayBinding="{Binding SectionLabel}" />
            <Picker x:Name="PickerGroup" />
            <Picker x:Name="PickerItem"
                    SelectedIndexChanged="PickerItem_OnSelectedIndexChanged"/>

And in C# CodeBehind:
    public class GroupingItem : ObservableCollection<string>
    {
        public string SectionLabel { get; set; }
    }

    readonly ObservableCollection<GroupingItem> _items = new ObservableCollection<GroupingItem>();
  // iOS only, take a margin at the top
            this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);

            //Male section created
            var item = new GroupingItem
    {
        SectionLabel = "Group 1",
    };
    _items.Add(SetGroupName(item));

    //Create a handsome section
            item = new GroupingItem
    {
        SectionLabel = "Group 2",
    };
    _items.Add(SetGroupName(item));

    //Create an actor section
            item = new GroupingItem
    {
        SectionLabel = "Group 3",
    };
    _items.Add(SetGroupName(item));

    //Set grouping item to ItemsSource of ListView
            MyListView.ItemsSource = _items;

            //Assign group name
    PickerGroup.Items.Add("Group 1");
    PickerGroup.Items.Add("Group 2");
    PickerGroup.Items.Add("Group 3");

            //Assign item name
            PickerItem.Items.Add("Name 1");
    PickerItem.Items.Add("Name 2");
    PickerItem.Items.Add("Name 3");
    PickerItem.Items.Add("Name 4");
    PickerItem.Items.Add("Name 5");
    PickerItem.Items.Add("Name 6");
    PickerItem.Items.Add("Name 7");
    PickerItem.Items.Add("Name 8");
    PickerItem.Items.Add("Name 8");
    PickerItem.Items.Add("Name 10");

    //Initial set of group names
            PickerGroup.SelectedIndex = 0;
}
private GroupingItem SetGroupName(GroupingItem groupingItem)
    {
        groupingItem.Add("Name 1");
        groupingItem.Add("Name 2");
        groupingItem.Add("Name 3");
        groupingItem.Add("Name 4");
        groupingItem.Add("Name 5");
        groupingItem.Add("Name 6");
        groupingItem.Add("Name 7");
        groupingItem.Add("Name 8");
        groupingItem.Add("Name 9");
        groupingItem.Add("Name 10");
        return groupingItem;
    }

   private void PickerItem_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        var selectedGroup = PickerGroup.Items[PickerGroup.SelectedIndex];
        var selectedItem = PickerItem.Items[PickerItem.SelectedIndex];
        MyListView.ScrollTo(selectedItem, selectedGroup, ScrollToPosition.Center, true);
        }







lundi 5 février 2018

TableView in Xamarin.Forms


TableView is a control that displays a list similar to the ListView as rows in horizontal orientation but it can present the children added manually in a rich visualization.
In TableView, we can't load the content as a source like ListView (ItemSource), we have to add elements manually.

In this article, I will explain how we can use this control.

1- How to use TableView


  <StackLayout HorizontalOptions = "Center" VerticalOptions = "Center">
            <TableView >
                <TableView.Root>
                    <TableRoot>
                        <TableSection Title="TableView Overview">
                            <TextCell Text="Text cell" Detail="Details"/>
                            <EntryCell Placeholder="Could you introduce something !"/>
                            <SwitchCell  Text = "My Switch" />
                        </TableSection>
                    </TableRoot>
                </TableView.Root>
            </TableView>
</StackLayout>


2- Public property list of TableView

HasUnevenRows property

Gets or sets a value indicating whether it can have non-uniform rows.
By setting the HasUnevenRows property to True, the height will be automatically changed according to the contents of the TableView.
  <TableView HasUnevenRows="True" >

Intent property

Gets or sets the intent of the table.
By using the Intent property, you can change to a TableView that fits your purpose.

Data

A table intended to contain an arbitrary number of similar data entries.
Example in XAML:

 <StackLayout HorizontalOptions = "Center" VerticalOptions = "Center">
            <TableView Intent="Data">
                <TableView.Root>
                    <TableRoot>
                        <TableSection Title="TableView having the property Intent=Data">
                            <TextCell Text="This is Xamarin ! TableView Control!" Detail="Details"/>
                            <EntryCell Placeholder="This is an Entry Cell to introduce a text!"/>
                            <SwitchCell Text="Select Yes/No!"/>
                        </TableSection>
                    </TableRoot>
                </TableView.Root>
            </TableView>
        </StackLayout>

· Menu

A table for use as a menu for selection.

· Settings

A table containing a series of switches, toggles, or other configurable configuration settings.

· Form

A table that is normally used to store the information contained in a form.


Root property

Gets or sets the root of the table.
You can assign cells to TableView by using the Root property. Actually , used it with all the code from the beginning.

RowHeight property

An integer representing the height of the item in the list. If HasUnevenRows is true, this property is ignored.
You can change the cell size by using the RowHeight property.
  <TableView RowHeight="100">

TableView in Code-behind

I will write the following code in the code behind 
InitializeComponent ();


            //iOS only, take a margin at the top
            Padding = new Thickness(0, top: Device.OnPlatform(20, 0, 0), right: 0, bottom: 0);

        // TableView
        var tableView = new TableView
        {
            //Set intent as "Form"
                    Intent = TableIntent.Form,

            //Assign to route
                    Root = new TableRoot("Configuration")
            {
                new TableSection("TableView having the property Intent=Form")
                {
                    //TextCell
                    new TextCell
                    {
                        Text = "This is Xamarin ! TableView Control!",
                        Detail = "Details",
                    },
 
                    //Switch Cell
                    new SwitchCell
                    {
                        Text = "Select Yes/No!"
                    },
 
                    //エントリーセル
                    new EntryCell
                    {
                        Label = "Entry Cell",
                        Placeholder = "This is an Entry Cell to introduce a text!"
                            }
                
                }
            }
        };
            // TableView Place only content as content
            Content = tableView;


jeudi 1 février 2018

Xamarin Notes — Xamarin.Forms: Layouts

As a definition, a layout is "a specialized subtype of a View, and ultimately acts as a container for other layouts or views.” A layout contains logic (XAML and code –behind in c#) to set the position and size of child controls and elements in applications.
Image title
In this part, we will organize our views (Controls: gather and display). We will describe the way of assembling views into a horizontal or vertical stack with the StackLayout panel.
But first, remember that this is an XML description of a page. I notice that the first namespace that’s focused there is:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Hondew"
             x:Class="Hondew.MainPage">

StackLayout

StackLayout allows you to stack views one about the others or side by side, it’s the layout the most used. Check out the docs for more details.
   <StackLayout>
        <Label x:Name="MainLable"
               HorizontalOptions="Center"
               FontSize="30"
               TextColor="Black"></Label>
    </StackLayout>
  • Orientation
Horizontal or Vertical. The default is Vertical.
<StackLayout Orientation="Horizontal"> or <StackLayout Orientation="Vertical">
  • Position with LayoutOptions
The view can be given VerticalOptions and HorizontalOptions depending on the view position relative to the layout. In this part, we will describe how we can assemble views into a horizontal or vertical stack with the StackLayout panel.
   <StackLayout Orientation="Horizontal">
           <Button x:Name="Button1" Text="Button1" BackgroundColor="Red"></Button>
            <Button x:Name="Button2" Text="Button2" BackgroundColor="Aqua"></Button>
  </StackLayout>
In our sample, we will assemble two buttons into a horizontal stack (first picture).
  <StackLayout Orientation="Vertical">
           <Button x:Name="Button1" Text="Button1" BackgroundColor="Red"></Button>
            <Button x:Name="Button2" Text="Button2" BackgroundColor="Aqua"></Button>
  </StackLayout>
Image title
VerticalOptions and HorizontalOptions use these values:
  • Start: it places the view at the beginning of the layout.
  • End: it is the opposite of Start, it places it in the end.
  • Fill: it places the view without a padding.
  • Center: it places the viewer in the middle within the layout.
  • How is the view aligned with the parent view?
    Image title
    <StackLayout>
            <Label HorizontalOptions="Start" BackgroundColor="Blue" Text="Start"></Label>
             <Label HorizontalOptions="End" BackgroundColor="Red" Text="End"></Label>
             <Label HorizontalOptions="Center" BackgroundColor="Yellow" Text="Center"></Label>
             <Label HorizontalOptions="Fill" BackgroundColor="Green" Text="Fill"></Label>
    </StackLayout>
    And in C#
                var stack = new StackLayout();
                var labelStart = new Label()
                {
                    HorizontalOptions = LayoutOptions.Start,
                    BackgroundColor = Color.Blue,
                    Text = "Start"
                };
                var labelEnd = new Label()
        {
            HorizontalOptions = LayoutOptions.End,
            BackgroundColor = Color.Red,
            Text = "End"
                };
                var labelCenter = new Label()
        {
            HorizontalOptions = LayoutOptions.Center,
            BackgroundColor = Color.Yellow,
            Text = "Center"
        };
        var labelFill = new Label()
        {
            HorizontalOptions = LayoutOptions.Fill,
            BackgroundColor = Color.Green,
            Text = "Fill"
        };
        stack.Children.Add(labelStart);
        stack.Children.Add(labelEnd);
        stack.Children.Add(labelCenter);
                stack.Children.Add(labelFill);
        Content = stack;
    Image title
    <StackLayout Orientation="Vertical">
              <Label HeightRequest="100" BackgroundColor="Blue" Text="One"/>
                <Label HeightRequest="50" BackgroundColor="Red" Text="Two"/>
               <Label HeightRequest="200" BackgroundColor="Yellow" Text="Three"/>
    </StackLayout>
    var stack = new StackLayout()
        {
            Orientation = StackOrientation.Vertical
        };
                var labelOne = new Label()
                {
                    HeightRequest = 100,
                    BackgroundColor = Color.Blue,
                    Text = "One"
                };
                var labelTwo = new Label()
        {
            HeightRequest = 50,
                    BackgroundColor = Color.Red,
            Text = "Two"
                };
                var labelThree = new Label()
        {
            HeightRequest = 200,
                    BackgroundColor = Color.Yellow,
            Text = "Three"
        };
        stack.Children.Add(labelOne);
        stack.Children.Add(labelTwo);
        stack.Children.Add(labelThree);
                Content = stack;

    • Spacing
    It can be an integer or decimal.
    Image title
    <StackLayout Orientation="Vertical" BackgroundColor="Gray">
                <StackLayout Orientation="Horizontal">
                    <Label  BackgroundColor="Blue" Text="Start"></Label>
                    <Label BackgroundColor="Red" Text="End"></Label>
                    <Label BackgroundColor="Yellow" Text="Center"></Label>
                </StackLayout>
                <StackLayout Orientation="Vertical" BackgroundColor="DarkBlue">
                    <Button x:Name="Button1" Text="Button1" BackgroundColor="Red"></Button>
                    <Button x:Name="Button2" Text="Button2" BackgroundColor="Aqua"></Button>
                </StackLayout>
    </StackLayout>
    If we add Spacing for the first StackLyout:
    <StackLayout Orientation="Horizontal" Spacing="-6"> or 
    <StackLayout Orientation="Horizontal" Spacing="0">
    We have this view:
    Image title
    • Sizing       
    Image title
    <StackLayout>
                <Label VerticalOptions="Start" BackgroundColor="Blue" Text="Start"></Label>
                <Label VerticalOptions="End" BackgroundColor="Red" Text="End"></Label>
                <Label VerticalOptions="Center" BackgroundColor="Yellow" Text="Center"></Label>
                <Label VerticalOptions="Fill" BackgroundColor="Green" Text="Fill"></Label>
    </StackLayout>
    Expand defines if the element will occupy more space if available.
    So, we add the Suffix Expand: If the parent view is larger than the combined size of all its children, (i.e. if additional space is available), then the space is proportioned amongst child views with that suffix. Those children will "occupy" their space, but do not necessarily "fill" it. We'll have a look at this behavior in the example below.
    No suffix: The children without the Expand suffix won't get additional space, even if we have available space.
    This is an example:
    Image title
      <StackLayout Orientation="Vertical" BackgroundColor="Gray" >
                <StackLayout Orientation="Horizontal" Spacing="10" Padding="50,20,100,150">
                    <Label  BackgroundColor="Blue" Text="Start"></Label>
                    <Label BackgroundColor="Red" Text="End"></Label>
                    <Label BackgroundColor="Yellow" Text="Center"></Label>
                </StackLayout>
                <StackLayout Orientation="Vertical" BackgroundColor="DarkBlue" Spacing="50">
                    <Button x:Name="Button1" Text="Button1" BackgroundColor="Red"></Button>
                    <Button x:Name="Button2" Text="Button2" BackgroundColor="Aqua"></Button>
                </StackLayout>
    </StackLayout>

    AbsoluteLayout

    AbsoluteLayout allows you to position a child element at an absolute requested position.
    Sometimes, you want to have more control over the positioning of objects on the screen, for example, you want to anchor them to the edges of the screen or you want to overlay multiple elements.
    In AbsoluteLayout, we use four values and eight flags.

    Values

    It can be Absolute Values (in Pixel) or Proportional Values (from 0 to 1)
    • Position:
      • X: for horizontal position of the view anchor.
      • Y: for the vertical position of the view anchor.
    • Size:
      • Width: it’s the width of our view.
      • Height: it defines the height of our view.
    Values are specified as a combination of bounds and a flag. LayoutBounds is a Rectangle consisting of four values: x, y, width, height.

    Flags

    It can be Absolute Flags (in Pixel) or Proportional Flags (from 0 to 1)
    • None: all these numbers are absolute values. (Values are in pixel).
    • All:  all numbers in layout bounds are propositional. (Values are from 0 to 1).
    • WidthProportional: interprets the Width value as proportional and all other values as absolute.
    • HeightProportional: interprets only the height value as proportional with all other values absolute.
    • XProportional: interprets the X value as proportional, while treating all other values as absolute.
    • YProportional: interprets the Y value as proportional, while treating all other values as absolute.
    • PositionProportional: interprets the X and Y values as proportional, while the size values are interpreted as absolute.
    • SizeProportional: interprets the Width and Height values as proportional while the position values are absolute.
    Refer to this link for more details. 
    Structure:
            <AbsoluteLayout>
                <BoxView Color="Olive"  
                         AbsoluteLayout.LayoutBounds="X, Y, Width, Height"
                         AbsoluteLayout.LayoutFlags="FlagsValue" />
            </AbsoluteLayout>
    Proportional example 1:
        <BoxView Color="Blue"  
                         AbsoluteLayout.LayoutBounds="0, 0, 0.1, 0.5"
                         AbsoluteLayout.LayoutFlags="All" />
    Proportional example 2:
          <BoxView Color="Blue"  
                         AbsoluteLayout.LayoutBounds="0, 0, 1, 0.5"
                         AbsoluteLayout.LayoutFlags="All" />
    Absolute Example 1:
      <BoxView Color="Blue"  
                         AbsoluteLayout.LayoutBounds="0, 75, 250, 410"
                         AbsoluteLayout.LayoutFlags="None" />
    Image title
    Image title

    RelativeLayout

    RelativeLayout uses a constraint to layout children. Go to this link for more details.
    Similar to AbsoluteLayout, with RelativeLayout, we can overlay elements on top of each other, but it's more powerful that AbsoluteLayout because you are able to apply a constraint to position or size of an element relative to another element. It offers more controls related to the position and size of the element.
    This is an example:

    Constraints

    • Type: it defines if this will be relative to the parent or to a view: we use as a value: RelativeToParent or Constant or RelativeToView.
    • Property: it defines what we need to use as the basis of the constraints. It can be Width or Height or X or Y.
    • Factor: it is dedicated to applying to the property value, this value a decimal between 0 and 1 and can be written in this way: 0.5è.5
    • Constant: it is the value to be used as an offset of the value.
    • ElementName: the name of the view that the constraint relative to, in case that we used the type RelativeToView.
    <ScrollView>
                <RelativeLayout>
                    <BoxView Color="Gray" HeightRequest="200" 
                        RelativeLayout.WidthConstraint="{ConstraintExpression 
                        Type=RelativeToParent,
                        Property=Width,
                        Factor=1}" />
                    <Button BorderRadius="35" 
                            x:Name="ImageCircleBack" 
                            BackgroundColor="Blue" 
                            HeightRequest="70" WidthRequest="70" 
                            RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=.5, Constant = -35}" 
                            RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Factor=0, Property=Y, Constant=70}" />
                 <Label Text="Hamida REBAÏ" FontAttributes="Bold" FontSize="26" HorizontalTextAlignment="Center" 
                           RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Factor=0, Constant=140}" 
                           RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}" />
                </RelativeLayout>
            </ScrollView>
    And we get this result:
    Image title
    Image title

    Grid

    Grid is like a table. It’s more is more versatile than a StackLayout, giving two dimensions to work with: columns and rows. It's also easy to align views across different rows. You can go to this link for more details.
    In this part, we will learn how to create a Grid and specify rows and columns.
    Image title
    <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Button Text="7" Grid.Row="1" Grid.Column="0"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="8" Grid.Row="1" Grid.Column="1"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="9" Grid.Row="1" Grid.Column="2"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="4" Grid.Row="2" Grid.Column="0"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="5" Grid.Row="2" Grid.Column="1"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="6" Grid.Row="2" Grid.Column="2"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="1" Grid.Row="3" Grid.Column="0"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="2" Grid.Row="3" Grid.Column="1"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="3" Grid.Row="3" Grid.Column="2"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="0" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="3"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
                <Button Text="/" Grid.Row="1" Grid.Column="3"
            BackgroundColor="#FFA500" TextColor="White"
            FontSize="36" BorderRadius="0" />
                <Button Text="X" Grid.Row="2" Grid.Column="3"
            BackgroundColor="#0000ff" TextColor="White"
            FontSize="36" BorderRadius="0" />
                <Button Text="-" Grid.Row="3" Grid.Column="3"
            BackgroundColor="#8000ff" TextColor="White"
            FontSize="36" BorderRadius="0" />
                <Button Text="+" Grid.Row="4" Grid.Column="3"
            BackgroundColor="#0080ff" TextColor="White"
            FontSize="36" BorderRadius="0" />
                <Button Text="C" Grid.Row="5" Grid.Column="0"
            BackgroundColor="#808080" TextColor="White"
            FontSize="36" BorderRadius="0" />
                <Button Text="=" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="3"
            BackgroundColor="#000066" TextColor="White"
            FontSize="36" BorderRadius="0" />
    </Grid>
    We start by defining the number of Rows and Columns using these tags inside the Grid.
    <Grid.RowDefinitions>
         <RowDefinition/>
         <RowDefinition/>
         <RowDefinition/>
         <RowDefinition/>
         <RowDefinition/>
         <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
         <ColumnDefinition/>
         <ColumnDefinition/>
         <ColumnDefinition/>
         <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    Image title
    After that, we will arrange views inside it.
    For example:
                <Button Text="7" Grid.Row="1" Grid.Column="0"
           BackgroundColor="White" TextColor="Black"
           FontSize="36" BorderRadius="0" />
    This button will be placed in the second row (Grid.Row="1") and first column (Grid.Column="0").
    Image title
    Image title
    To define the Height of the Row, we use the Height attribute:
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto" />
    This value can be Auto or 100 or *, we can use 2* (even n*).
    To define the Width of the Column, we use the Width attribute:
    <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
    This value can be Auto or 100 or *, we can use 2* (even n*).
    <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="100" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="2*"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Column="0" Grid.Row="0" Text="1" BackgroundColor="Red" ></Label>
                <Label Grid.Column="1" Grid.Row="0" Text="2" BackgroundColor="Red"></Label>
                <Label Grid.Column="0" Grid.Row="1" Text="3" BackgroundColor="Red"></Label>
                <Label Grid.Column="1" Grid.Row="1" Text="4" BackgroundColor="Red"></Label>
                <Label Grid.Column="0" Grid.Row="2" Text="5" BackgroundColor="Red"></Label>
                <Label Grid.Column="1" Grid.Row="2" Text="6" BackgroundColor="Red"></Label>
            </Grid>
    Image title

    ScrollView

    ScrollView is a scrolling content.
    Without the use of ScrollView:
    <StackLayout>
                <BoxView Color="Blue" HeightRequest="200"/>
                <BoxView Color="Green" HeightRequest="200"/>
                <BoxView Color="Firebrick" HeightRequest="200"/>
                <BoxView Color="YellowGreen" HeightRequest="300"/>
    </StackLayout>
    Image title
    In our case, the Yellow Green BoxView is not displayed, so when we add the ScrollView, we will be able to get all the content by scrolling. ScrollView will add scroll indicators to the UI. We can use the orientation property if I want to request the horizontal Scroll Indicator or Vertical to display it vertically or both to display both of them.
    <ScrollView Orientation="Horizontal"> or <ScrollView Orientation="Vertical"> or <ScrollView Orientation="Both">
    <ScrollView>
                <StackLayout>
                    <BoxView Color="Blue" HeightRequest="200"/>
                    <BoxView Color="Green" HeightRequest="200"/>
                    <BoxView Color="Firebrick" HeightRequest="200"/>
                    <BoxView Color="YellowGreen" HeightRequest="300"/>
    </StackLayout>
    </ScrollView>
    Image title
    For more details, go to this link.
    ScrollView is most used to display a list (ListView).
    We will talk about Frame in the next article).