Computer Magic Logo
Add controls programmatically

Tuesday, May 3, 2016

Published by Aristotelis Pitaridis

The following example demonstrates how to add programmatically controls to an Absolute Layout. First we have the XAML which contains an AbsoluteLayout.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.Page1">
  <AbsoluteLayout x:Name="MyAbsoluteLayout">
  </AbsoluteLayout>
</ContentPage>

Now we can use this AbsoluteLayout in order to add controls.

public partial class Page1 : ContentPage
{
    public Page1 ()
    {
        InitializeComponent ();

        MyAbsoluteLayout.Children.Add(
            new BoxView
            {
                Color = Color.Blue
            },
            new Rectangle(0, 0, 200, 200));

        MyAbsoluteLayout.Children.Add(
            new BoxView
            {
                Color = Color.Red
            },
            new Rectangle(200, 0, 200, 200));

        MyAbsoluteLayout.Children.Add(
            new BoxView
            {
                Color = Color.Green
            },
            new Rectangle(0, 200, 200, 200));

        MyAbsoluteLayout.Children.Add(
            new BoxView
            {
                Color = Color.Yellow
            },
            new Rectangle(200, 200, 200, 200));
    }
}