0
votes

I am using listview to show contacts number in xamarin forms. On clicking any cell I want to change content of only that particular cell. Following is my code:

    lst_view.ItemSelected += async (object sender, SelectedItemChangedEventArgs e) =>
        {
            var con =(Contact)e.SelectedItem;
            int index=contactList.IndexOf(con);

            if (con.is_selected)
            {
                contactList[index].is_selected = false;
                contactList[index].img = "";
            }
            else{
                contactList[index].is_selected = true;
                contactList[index].img = "selected_checkbox.jpeg";
            }

            lst_view.ItemTemplate = new DataTemplate(typeof(ContactsItemCell));
        };

It is working fine but as end I am giving new datatemplate thats on clicking cell whole listview redraw and which is annoying experience. I just want to update that cell, not whole listview. By the way on clicking I am changing image of that cell through binding with valueconverter.

1

1 Answers

1
votes

From the code you displayed, there is a much simpler way to do this without changing the ListView.ItemTemplate. It looks like you are trying to have the SelectedItem in a ListView change it's state to a "Selected" state where you display a checkbox image.

This should be done by utilizing the OnBindingContext override in the Xamarin.Forms.ViewCell class. In this override, you can gain access to the BindingContext of the ViewCell which is the model of information to be displayed. In here you should be checking the "is_selected" property and setting the Image into the ListView.ViewCell to the appropriate image stored in the application.

To have the changes be updated in the ItemSelected, you would need to call OnPropertyChanged for the Collection the ListView is bound to. The way you are changing the SelectedItem model is correct, but you need to ensure that happens in the source collection of data. Calling OnPropertyChanged will trigger Xamarin.Forms to update the ViewCells from the bound source.

If you needed to have completely different ViewCells displayed (not just change the selected image), you shouldn't update the ItemTemplate of the ListView in the ItemSelected event handler and shouldn't change the ItemTemplate ever. You should create a DataTemplateSelector. You can than provide a DataTemplate based on the model object to be displayed.

I hope this helps!

Disclosure: I work for Xamarin/Microsoft