How to remove Children from an AbsoluteLayout in Xamarin.Forms?

kaolick picture kaolick · Sep 5, 2014 · Viewed 9.3k times · Source

In my app I use a Xamarin.Forms AbsoluteLayout. I have a custom menu bar. When I clicked on a menu button, the main content (a View) of my AbsoluteLayout is supposed to be replaced.

So far I can only achieve that by adding a new child and setting its layout bounds using Children.Add() and SetLayBounds(). But this way I'm adding more and more children and never remove them.

What is the proper way to remove a child from an AbsoluteLayout?

Answer

Stephane Delcroix picture Stephane Delcroix · Sep 5, 2014

.Children implements IList<View> (and ICollection<View>, IEnumerable<View>, Ienumerable) so you can use at your best convenience:

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

provide you know the index of your view in .Children, you can also replace the element in place:

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

but that gives you less options than the Children.Add (...) overrides and you'll have to use SetLayoutBounds and SetLayoutFlags.