How to remove children from AbsoluteLayout in Xamarin.Forms?

In my application I use Xamarin.Forms AbsoluteLayout. I have a menu bar. When I pressed the menu button, the main content (a View) of mine AbsoluteLayoutshould be replaced.

So far, I can only achieve this by adding a new child and setting the boundaries of his layout with Children.Add()and SetLayBounds(). But in this way I add more and more children and never delete them.

What is the correct way to remove a child from AbsoluteLayout?

+4
source share
2 answers

.Children IList<View> ( ICollection<View>, IEnumerable<View>, Ienumerable), :

  • layout.Children.RemoveAt (position),
  • layout.Children.Remove (view),
  • layout.Children.Clear ()

.Children, :

layout.Children[position] = new MyView ();

, Children.Add (...), SetLayoutBounds SetLayoutFlags.

+9

, RemoveAt AbsoluteLayout.Children.

Remove (View), .

        StackLayout objStackLayout = new StackLayout()
        {
        };
        //
        AbsoluteLayout objAbsoluteLayout = new AbsoluteLayout()            
        {
        };
        //
        BoxView objBox1 = new BoxView()
        {
            Color = Color.Red,
            WidthRequest = 50,
            HeightRequest = 50,
        };
        objAbsoluteLayout.Children.Add(objBox1, new Point(100,100));
        System.Diagnostics.Debug.WriteLine("Children Count : " + objAbsoluteLayout.Children.Count);
        //
        BoxView objBox2 = new BoxView()
        {
            Color = Color.Green,
            WidthRequest = 50,
            HeightRequest = 50,
        };
        objAbsoluteLayout.Children.Add(objBox2, new Point(200, 200));
        System.Diagnostics.Debug.WriteLine("Children Count : " + objAbsoluteLayout.Children.Count);
        //
        Button objButton1 = new Button()
        {
            Text = "Remove First Child"
        };
        objButton1.Clicked += ((o2, e2) =>
            {
                if (objAbsoluteLayout.Children.Count > 0)
                {
                    // To Remove a View at a specific index use:-
                    objAbsoluteLayout.Children.RemoveAt(0);
                    //
                    DisplayAlert("Children Count", objAbsoluteLayout.Children.Count.ToString(), "OK");
                }
                else
                {
                    DisplayAlert("Invalid", "There are no more children that can be removed", "OK");
                }
            });

        //
        objStackLayout.Children.Add(objAbsoluteLayout);
        objStackLayout.Children.Add(objButton1);
0

All Articles