Well, it’s been a while. Let’s dive right into it, shall we?
WHAT IS AN OBSERVABLE COLLECTION?
An Observable Collection is basically a list of items that can be displayed on a XAML page. It inherently possesses some basic INOTIFYPROPERTYCHANGED (INPC) traits, allowing the UI to be automatically updated whenever the Observable Collection is changed – without the need to call any functions.
The implementation of an Observable Collection can be broken down into three stages.
STEP 1: Initializing the Observable Collection
Create the Observable Collection attribute in your ViewModel (BMIVIEWMODEL.cs) and initialize it in the constructor. Note that in this case, we are creating an Observable Collection holding items of class HUMAN (found in the Models folder).
STEP 2: Updating the Observable Collection.
This section consists of changing the Command executed when CALCULATE BMI is clicked. It will now calculate the BMI and add the result (as a HUMAN object) to our Observable Collection.
The magic here is that the BMI is just being added to the Observable Collection, and that’s it. Nothing more is being done – no function or INPC calls. This is simply because Observable Collections already take care of that on their own.
STEP 3: Adjust the GUI (BMIVIEW.xaml) to cater for a LISTVIEW.
The LISTVIEW is essentially the Xamarin Forms control that allows the application to display any kind of list on the GUI. It is often accompanied by a DATATEMPLATE which dictates how the data in the list should be presented on-screen.
Adding this section and the proper bindings to your code should do the trick.
Let’s break it down.
First, the whole thing is stuffed into a SCROLLVIEW to allow scrolling.
Second, the LISTVIEW ITEMSOURCE is bound to the Observable Collection (LISTHUMANS). This is basically instructing the LISTVIEW to fetch all its items from our Observable Collection.
Finally, the LISTVIEW will present the data based on the DATATEMPLATE, which basically is providing the XAML codes for how the List Items should be displayed. Notice how the attributes of the HUMAN class is being used in the BINDINGS.
AND WE ARE DONE HERE.
That’s it – the Observable Collection was implemented on all fronts.
Be sure to leave a comment if anything is missing (or just to drop in a feedback).