Child control Event handling in Listview using Xamarin.Forms

We can add child controls to Listview in Xamarin.Forms. In order to see the child control in action we will take an example. Let’s display a list of data in the Listview and perform delete option on the list data per row basis.

Since we need to add multiple columns in the list view, we need to use the DataTemplate to define the custom view. Let’s use a model class to assign the data to the custom view.

We will use XAML to design a Listview

In the above XAML, we have used the StackLayout as the parent container for the child views. It contains a Label and a Listview. UI Control is ready.

Time to add event to the child control
We will replace the Button control in the above XAML with the following line

With this new line we have added the Clicked Event handler to the Button control and also a CommandParameter in order to locate the item at runtime.

How the final XAML look like then ?

Code behind for this XAML

Running the app
Running fine. OOOPSSSSSSS… but the deletion is not working. That’s correct. Because, the item is getting deleted from the collection but the ItemSource is not getting refreshed.

What we need to do then ?????
Pretty simple. Let’s use an ObservableCollection to assign the ItemSource.

Modifying the Model Class

Added a new ObservableCollection class which will be used as the ItemSource of the Listview.

Small changes in the code behind

We have modified the code and added the ObservableCollection object in the ItemSource. So that the delete operation gets reflected in the Listview.

How is the output ?
Now, we can see the immediate effect of Delete button as soon as we click it.

Happy coding 🙂

Categories: Android, Cross Platform Mobile App, CSharp, iOS, Visual Studio, Windows Phone, Xamarin, XAML

Leave a Reply

%d bloggers like this: