UI, Xamarin

Creating Accordions in Xamarin Forms

Sometimes, we need to include in our ListViews, some additional options to make better the user experience and the usability on the screen. That’s why now I’m going to explain to you how to do an Expandable ListView (Accordion) in Xamarin Forms. Let’s see!

Which steps do I have to do?

1⃣ Step one:  Let’s create the Model

In this example, we will be working with the MVVM pattern using a Music list as an example. Here we just have to add the attributes that we will be needing in our application later.

⚠ Important:  You can play with the attributes, changing the values to whatever you need but the only attribute that you can not forget to add the “IsVisible” attribute because this is the most important to create to get the desired effect.

2⃣ Step two:  Let’s create the ViewModel

To understand clearly what we are doing, I will explain you step by step the MainViewModel class

⚪ In the first block we have an ObservableCollection of our Music Model class. The ObservableCollection represents a dynamic data collection that provides notifications when items got an event (Added, removed, refreshed). You can read more information here.

⚪ Inside the constructor method, we have to add the attributes information to fill the collection, to be able to display in our example.

⚪ UpdateMusic method, help us update the visible states from each item of the ListView.

⚪ HideOrShowMusic method is responsible to change the Listview item visible state when the item gets selected.

Finally, we got the MainViewModel class.

3⃣ Step three:  Let’s a create a Custom Renderer to get a right behavior on IOS

⚪ Add a new class and inherit from the ListView class. In this case, I created the CustomListView class.

⚪ On the IOS Project, create the following class:

⚠ You can read more information about Custom Renderer here.

4⃣ Step four:  Let’s create the View

In the XAML, we have to do the following steps:

⚪ Add the BindingContext source to fill the XAML. In this case with the MainViewModel class.

⚪ Add the ItemTapped event. This event allows us to handle what will be happening when some item is selected.

⚪ Add the following namespace. (Controls is the folder that contains the CustomListView class.)

Finally, Let’s to Binding with every attributes I needed. It’s worthy of note that in the example, the Layout is Binded with the “IsVisible” attribute.

⚠ Here, instead of ListView control, I just added the custom rendered created above and this must be named as the following syntax: controls:CustomListView.

Done. Enjoy your accordion 😎

Click to see an example in my GitHub.

Spanish post:   https://medium.com/@reyes.leomaris/creando-acordeones-en-xamarin-forms-5abe9c9b884f 

References:      https://www.youtube.com/watch?v=GG10QPrRC3w&t=16s&app=desktop

Tagged , , ,

2 thoughts on “Creating Accordions in Xamarin Forms

Leave a Reply

Your email address will not be published. Required fields are marked *