Search code examples
c#xamarin.formsxamarin-studio

Create line use BoxView in Xamarin Forms


I need to create a line which is a made up of multiple BoxViews (WidthRequest=0.20830 and HeightRequest=5 for every BoxView). There will be 1440 BoxViews in a sequence arranged in way that it will create a line(approximately WidthRequest=300).

My Code -

public partial class timeManagement : ContentPage
{
    double oneMinute=0.20833333;
    public timeManagement ()
    {
        InitializeComponent ();
        StackLayout stack = new StackLayout{Orientation=StackOrientation.Horizontal,                
        };

        for(int i=1;i<=14;i++)
        {
            BoxView piece_ofLine = new BoxView
            { 
                HeightRequest=5,
                WidthRequest=5,
                Color=Color.Red
            };

            if (i >= 5 && i <= 9) {
                stack.Children.Add (piece_ofLine);
                piece_ofLine.Color = Color.Green;
            } else {
                stack.Children.Add (piece_ofLine);
                piece_ofLine.Color = Color.Red;
            }

        }


        Content = new StackLayout {
            Padding =50, 
            Spacing=0,

            Children = {
                stack
            }
        };

    }
}

And output is-enter image description here

But I want all boxes side by side so it will appear like a single line.


Solution

  • There are a few issues here

    1. The default orientation for a StackLayout is Vertical so you would need to set that on the stack variable

    2. You would need to create a new instance for each BoxView that you add to the stack. Otherwise it will just keep adding the same one over and over. And in the end you would just have one.

    3. I assume that you would want them directly to the side of each other. If this is the case, I think that it would be safest to explicitly set the Spacing of your StackLayout to 0