Many users of JQuery UI (both Mobile as well as web) are quite fond of accordion user control and ask for the same or a similar kind of control in Xamarin/ Xamarin Forms. As we all know that Xamarin forms controls are an abstraction to the native controls available in respective native platforms and since there is no accordion control available in any of the native mobile frameworks it’s not available as an out-of-the-box control in Xamarin Forms. So in this article we will be creating a simple accordion user-control using simple Xamarin Forms controls like Button and ContentView.

Firstly, we need to understand the functionality of an accordion, as per Wikipedia the developer's definition of an accordion is:

And that’s exactly what I have done.

The ‘Accordion’ class is extended from ContentView class of Xamarin; forms in which I am creating an accordion from list ‘AccordianSource’ objects on DataBind Method of the Class. The code of ‘Accordion’ user control is as follows:
  1. public class Accordion: ContentView
  2. {
  3. #region Private Variables
  4. List < AccordionSource > mDataSource;
  5. bool mFirstExpaned = false;
  6. StackLayout mMainLayout;
  7. #endregion
  8. public Accordion()
  9. {
  10. var mMainLayout = new StackLayout();
  11. Content = mMainLayout;
  12. }
  13. public Accordion(List < AccordionSource > aSource)
  14. {
  15. mDataSource = aSource;
  16. DataBind();
  17. }
  18. #region Properties
  19. public List < AccordionSource > DataSource
  20. {
  21. get
  22. {
  23. return mDataSource;
  24. }
  25. set
  26. {
  27. mDataSource = value;
  28. }
  29. }
  30. public bool FirstExpaned
  31. {
  32. get
  33. {
  34. return mFirstExpaned;
  35. }
  36. set
  37. {
  38. mFirstExpaned = value;
  39. }
  40. }
  41. #endregion
  42. public void DataBind()
  43. {
  44. var vMainLayout = new StackLayout();
  45. var vFirst = true;
  46. if (mDataSource != null)
  47. {
  48. foreach(var vSingleItem in mDataSource)
  49. {
  50. var vHeaderButton = new AccordionButton()
  51. {
  52. Text = vSingleItem.HeaderText,
  53. TextColor = vSingleItem.HeaderTextColor,
  54. BackgroundColor = vSingleItem.HeaderBackGroundColor
  55. };
  56. var vAccordionContent = new ContentView()
  57. {
  58. Content = vSingleItem.ContentItems,
  59. IsVisible = false
  60. };
  61. if (vFirst)
  62. {
  63. vHeaderButton.Expand = mFirstExpaned;
  64. vAccordionContent.IsVisible = mFirstExpaned;
  65. vFirst = false;
  66. }
  67. vHeaderButton.AssosiatedContent = vAccordionContent;
  68. vHeaderButton.Clicked += OnAccordionButtonClicked;
  69. vMainLayout.Children.Add(vHeaderButton);
  70. vMainLayout.Children.Add(vAccordionContent);
  71. }
  72. }
  73. mMainLayout = vMainLayout;
  74. Content = mMainLayout;
  75. }
  76. void OnAccordionButtonClicked(object sender, EventArgs args)
  77. {
  78. foreach(var vChildItem in mMainLayout.Children)
  79. {
  80. if (vChildItem.GetType() == typeof(ContentView)) vChildItem.IsVisible = false;
  81. if (vChildItem.GetType() == typeof(AccordionButton))
  82. {
  83. var vButton = (AccordionButton) vChildItem;
  84. vButton.Expand = false;
  85. }
  86. }
  87. var vSenderButton = (AccordionButton) sender;
  88. if (vSenderButton.Expand)
  89. {
  90. vSenderButton.Expand = false;
  91. }
  92. else vSenderButton.Expand = true;
  93. vSenderButton.AssosiatedContent.IsVisible = vSenderButton.Expand;
  94. }
  95. }
This control has one public method ‘DataBind’ and two public properties ‘FirstExpaned’ and ‘DataSource’. ’DataBind’ Method will be used when we use the control with XAML page as the control will not be initialized with data source passed. ‘FirstExpaned’ is a boolean to decide whether the control should appear with all items collapsed or first one expanded and ‘DataSource’ Property of the control will require the list of ‘AccordionSource’ class defined as below:
  1. using System;
  2. public class AccordionSource
  3. {
  4. public string HeaderText
  5. {
  6. get;
  7. set;
  8. }
  9. public Color HeaderTextColor
  10. {
  11. get;
  12. set;
  13. }
  14. public Color HeaderBackGroundColor
  15. {
  16. get;
  17. set;
  18. }
  19. public View ContentItems
  20. {
  21. get;
  22. set;
  23. }
  24. }
The property names of the class are pretty self explanatory. The three properties containing ‘Header’ are for the Header button created for each accordion item and the ContentItems is of View class so that we can put any container object inside it like ListView, StackView etc. In order to check whether the accordion header is expanded or not and to identify the Content associated with the button in order to show/hide, we require a button with some extra properties and we will get those by following ‘AccordionButton’ Class:
  1. public class AccordionButton: Button {
  2. #region Private Variables
  3. bool mExpand = false;
  4. #endregion
  5. public AccordionButton() {
  6. HorizontalOptions = LayoutOptions.FillAndExpand;
  7. BorderColor = Color.Black;
  8. BorderRadius = 5;
  9. BorderWidth = 0;
  10. }#region Properties
  11. public bool Expand {
  12. get {
  13. return mExpand;
  14. }
  15. set {
  16. mExpand = value;
  17. }
  18. }
  19. public ContentView AssosiatedContent {
  20. get;
  21. set;
  22. }#endregion
  23. }
This completes the code of our user control which can be found in the ‘accodion.cs’ class in example code. Now let''s see how to use this control in a sample application. In the application there is an accordion containing 3 Items. First one is a list, second is static data and third is again list.

The ‘XamlExample’ page have used this control using following code in XAML:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ContentPage
  3. xmlns="http://xamarin.com/schemas/2014/forms"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  5. xmlns:ctrl="clr-namespace:AccordionEx;assembly=AccordionEx" x:Class="AccordionEx.XamlExample" Title="XAML Example">
  6. <ContentPage.Content>
  7. <ctrl:Accordion x:Name="MainOne" />
  8. </ContentPage.Content>
  9. </ContentPage>
And the following code in the code behind constructor of the page:
  1. public XamlExample ()
  2. {
  3. InitializeComponent ();
  4. MainOne.DataSource = GetSampleData ();
  5. MainOne.DataBind ();
  6. }
The ‘CodeExample’ page has used this control directly in the code file using the following code:
  1. public CodeEaxmple()
  2. {
  3. Title = "Code Example";
  4. var vAccordionSource = GetSampleData();
  5. var vAccordionControl = new Accordion(vAccordionSource);
  6. Content = vAccordionControl;
  7. }
In both the example pages method ‘GetSampleData’ is used to get the sample data to bind with the accordion user control. The code of ‘GetSampleData’ method is as follows:
  1. public List < AccordionSource > GetSampleData()
  2. {
  3. var vResult = new List < AccordionSource > ();
  4. #region First List View
  5. var vListOne = new List < SimpleObject > ();
  6. for (var iCount = 0; iCount < 6; iCount++)
  7. {
  8. var vObject = new SimpleObject()
  9. {
  10. TextValue = "ObjectNo-" + iCount.ToString(),
  11. DataValue = iCount.ToString()
  12. };
  13. vListOne.Add(vObject);
  14. }
  15. var vListViewOne = new ListView()
  16. {
  17. ItemsSource = vListOne,
  18. ItemTemplate = new DataTemplate(typeof(ListDataViewCell))
  19. };
  20. vListViewOne.ItemTapped += OnListItemClicked;
  21. #endregion# region Second List
  22. var vListTwo = new List < SimpleObject > ();
  23. var vObjectRavi = new SimpleObject()
  24. {
  25. TextValue = "S Ravi Kumar",
  26. DataValue = "1"
  27. };
  28. vListTwo.Add(vObjectRavi);
  29. var vObjectFather = new SimpleObject()
  30. {
  31. TextValue = "Father",
  32. DataValue = "2"
  33. };
  34. vListTwo.Add(vObjectFather);
  35. var vObjectTrainer = new SimpleObject()
  36. {
  37. TextValue = "Trainer",
  38. DataValue = "2"
  39. };
  40. vListTwo.Add(vObjectTrainer);
  41. var vObjectConsultant = new SimpleObject()
  42. {
  43. TextValue = "Consultant",
  44. DataValue = "2"
  45. };
  46. vListTwo.Add(vObjectConsultant);
  47. var vObjectArchitect = new SimpleObject()
  48. {
  49. TextValue = "Architect",
  50. DataValue = "2"
  51. };
  52. vListTwo.Add(vObjectArchitect);
  53. var vListViewTwo = new ListView()
  54. {
  55. ItemsSource = vListTwo,
  56. ItemTemplate = new DataTemplate(typeof(ListDataViewCell))
  57. };
  58. vListViewTwo.ItemTapped += OnListItemClicked;
  59. #endregion
  60. #region StackLayout
  61. var vViewLayout = new StackLayout()
  62. {
  63. Children = {
  64. new Label
  65. {
  66. Text = "Static Content:"
  67. },
  68. new Label
  69. {
  70. Text = "Name : S Ravi Kumar"
  71. },
  72. new Label
  73. {
  74. Text = "Roles : Father,Trainer,Consultant,Architect"
  75. }
  76. }
  77. };
  78. #endregion
  79. var vFirstAccord = new AccordionSource()
  80. {
  81. HeaderText = "First",
  82. HeaderTextColor = Color.Black,
  83. HeaderBackGroundColor = Color.Yellow,
  84. ContentItems = vListViewTwo
  85. };
  86. vResult.Add(vFirstAccord);
  87. var vSecond = new AccordionSource()
  88. {
  89. HeaderText = "Second ",
  90. HeaderTextColor = Color.White,
  91. HeaderBackGroundColor = Color.FromHex("#77d065"),
  92. ContentItems = vViewLayout
  93. };
  94. vResult.Add(vSecond);
  95. var vThird = new AccordionSource()
  96. {
  97. HeaderText = "Third",
  98. HeaderTextColor = Color.White,
  99. HeaderBackGroundColor = Color.Purple,
  100. ContentItems = vListViewOne
  101. };
  102. vResult.Add(vThird);
  103. return vResult;
  104. }
In the above GetSampleData() method as the ListView objects are created on runtime, they require a custom view cell (got from ‘ListDataViewCell’) which shows the ‘TextValue’ property of the ‘SimpleObject’ class in a Label inside Stacklayout. The code of both the classes are in ‘App.cs’ file so that they can be utilized from both the example pages.

The code of ‘ListDataViewCell’ and ‘SimpleObject’ class are as follows:
  1. public class ListDataViewCell: ViewCell
  2. {
  3. public ListDataViewCell()
  4. {
  5. var label = new Label()
  6. {
  7. Font = Font.SystemFontOfSize(NamedSize.Default),
  8. TextColor = Color.Blue
  9. };
  10. label.SetBinding(Label.TextProperty, new Binding("TextValue"));
  11. label.SetBinding(Label.ClassIdProperty, new Binding("DataValue"));
  12. View = new StackLayout()
  13. {
  14. Orientation = StackOrientation.Vertical,
  15. VerticalOptions = LayoutOptions.StartAndExpand,
  16. Padding = new Thickness(12, 8),
  17. Children = {
  18. label
  19. }
  20. };
  21. }
  22. }
  23. public class SimpleObject
  24. {
  25. public string TextValue
  26. {
  27. get;
  28. set;
  29. }
  30. public string DataValue
  31. {
  32. get;
  33. set;
  34. }
  35. }
Apart from the above code, sample application contains a ‘HomePage’ (written in XAML as I like it more) with two buttons to display the XAML Example and CodeExample page. The code of HomePage is as follows:

XAML Code:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ContentPage
  3. xmlns="http://xamarin.com/schemas/2014/forms"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="AccordionEx.HomePage" Title="Accordion Example" >
  5. <ContentPage.Resources>
  6. <ResourceDictionary>
  7. <Style TargetType="Button">
  8. <Setter Property="BorderRadius" Value="10" />
  9. <Setter Property="BorderWidth" Value="2" />
  10. <Setter Property="WidthRequest" Value="150" />
  11. <Setter Property="HeightRequest" Value="150" />
  12. <Setter Property="HorizontalOptions" Value="Center" />
  13. <Setter Property="VerticalOptions" Value="Center" />
  14. <Setter Property="FontSize" Value="Medium" />
  15. <Setter Property="TextColor" Value="Red" />
  16. </Style>
  17. </ResourceDictionary>
  18. </ContentPage.Resources>
  19. <ContentPage.Content>
  20. <StackLayout VerticalOptions = "Center">
  21. <Button Text="Xaml Page" Clicked="OnXamlClicked" />
  22. <Button Text="Code Page" Clicked="OnCodeClicked" />
  23. </StackLayout>
  24. </ContentPage.Content>
  25. </ContentPage>
Code Behind C# code:
  1. public partial class HomePage: ContentPage
  2. {
  3. public HomePage()
  4. {
  5. InitializeComponent();
  6. }
  7. public void OnXamlClicked(object sender, EventArgs args)
  8. {
  9. Navigation.PushAsync(new XamlExample());
  10. }
  11. public void OnCodeClicked(object sender, EventArgs args)
  12. {
  13. Navigation.PushAsync(new CodeEaxmple());
  14. }
  15. }
The above written ‘HomePage’ is invoked in ‘App.cs’ constructor using Navigation Page, the code for same is as follows:
  1. public App ()
  2. {
  3. // The root page of your application
  4. MainPage = new NavigationPage(new HomePage());
  5. }
This is how the sample application looks on emulators:

iPhone

Xamarin Android Player:

Xamarin Android Player


The source code of sample application containing accordion user control and pages using the control can be downloaded from Github.

In the above post I have created a bare bone, accordion user control which anyone can customize as per their requirements, let me know if I have missed anything.
Read more articles on Xamarin: