Stop doing IsVisible=“true/false” to Show/Hide Views in RunTime in Xamarin Forms

When developing UI a common use case is to hide/show a View according to a certain condition, when thinking on how to do this the first thing that comes to mind is to add an IsVisible property and just hide/show it according to a condition but doing that has performance implications since hiding an element does not remove it from the UI, which means that if you have 10 views you will have all of them loaded in memory even when not visible.

Instead of doing that there are better alternatives. In this article, I’m going to provide some options.

Before starting

To illustrate the different approaches, I will use a simple TabbedView that has 2 buttons, one for Tab 1 and Tab2.

Check the ViewModel here.

—–

Using Control Template

Control template is a very handy Xamarin Forms functionality that helps you to separate the user interface (UI) of a custom view or page from the specific logic that implements the control or page. If you want to know more about it, I recommend you can check this great article by Xamboy.


1.Create separate views

In my case, I’ll create one for Tab1 and another one for Tab2

As you can see the view has a ContentPresenter, this is where the tab will be placed once we connect those views with the Page.


2.Add the views as ControlTemplates in the ResourceDictionary on the page that you want to use them

You can also add it to the App.xaml, if you are planning to use it in many places around the project.


3. Assign the control template according to the condition

In this case, I used Triggers, but you can do it with converters or in C# code behind if you like.

And that’s all.

——-

Using a Carousel View

Using a carousel view is another alternative to achieve this, it does not behave as Control Templates, since it will keep the elements in memory once it loads but will load the views on demand and provides the advantage of being able to swipe to change the view.


1. Create separate views


2. Create a DataTemplateSelector


3. Import the reference of the DataTemplateSelector to your XAML


4. Add the CarouselView

That’s all for now, you can check the full source code here.

Happy coding!

You may also like

3 Comments