When designing a View (Page) we need to take into consideration that there might be a lot of content to show. Typically we should use a ListView, which by default is scrollable. However, what if you have to show more than one ListView on a single page? Nesting ScrollViews is a very bad practice that should be avoided unless natively supported. In this case it will most probably make sense to put all the content within a single ScrollView. But how? Here is where the Repeater or BindableStackLayout comes into play.
Custom Control
In order to solve the problem described in the Intro, we will have to extend a StackLayout and expose the next bindable properties:
ItemsSource - Gets/sets the source of items to template and display.
ItemDataTemplate - Gets/sets the item template.
Title - Gets/sets the header/title of the control.
The implementation is very simple and does not require any custom renderers since we are simply going to reuse a layout that arranges child views vertically or horizontally. We are going to use BindableProperties in order to be able to react to value changes in a real time.
Here is a very simple implementation in ±50 lines of code:
All the “stuff” is happening within the PopulateItems method which is called when a value of ItemSource property is changing. We simply iterate through the collection of items and add them as children to the root view. Please note that each child is represented by ItemDataTemplate, so all we have to do, is to invoke CreateContent method that will be generate the view for us.
Usage example:
Conclusion
The implementation above is very simple, however some corner cases are not handled on purpose. This can be a nice homework for you to discover and handle those. The code above is fully available on github.