Danny Goodall Danny Goodall - 2 months ago 12
iOS Question

Populating ListView with NavigationParameters?

In my Xamarin Forms application, I have a ListView with different cells, using DataTemplates and DataTemplateSelectors. For one type of cell, it has a button on it, which when tapped, navigates to another page which contains just a ListView which is made up of only strings.

My problem arises from the OnNavigatedTo method being called after the page has loaded, and therefore the list that I am passing to this new 'ListView only' page, updates the value that I bind the ListView to after the ListView is created and populated, but it is populated with nothing because the data comes from the previous page via the OnNavigatedTo method.

public class ListPageViewModel : _ViewModelBase
{
private INavigationService _navigationService;

public ListPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
_strings = new List<string>()
{
"Jaguar", "Elephant", "Nemo", "Cat", "Dog", "Iguana", "Puma", "Crow", "Hawk", "Owl", "Badger", "Meerket",
"Shark", "Whale", "Monkey", "Snake", "Lion", "Zebra", "Hippo", "Squirrel", "Rhino", "Bear", "Moose",
"Camel", "Chicken", "Cow", "Sheep", "Turkey", "Jellyfish", "Salmon", "Parrot", "Wolf", "Gecko"
// Placeholder before we have lists of customers
};
}

private IEnumerable<string> _strings;
public IEnumerable<string> Strings { get { return _strings; } set { SetProperty(ref _strings, value); } }

public override void OnNavigatedTo(NavigationParameters parameters)
{
base.OnNavigatedTo(parameters);

if (parameters.ContainsKey("dataList"))
{
_strings = (List<string>)parameters["dataList"];
}
}
}


So when I navigate to this page, the
_strings
list is first populated with the list of animals, and then the page loads showing all the animals in the ListView, and then after the ListView has loaded it changes the value of the
_strings
list to be the same as the list passed along with the NavigationParameters. So how do I make the ListView update every time the
_strings
list is changed or updated?

Answer

Either

Strings = (List<string>)parameters["dataList"];

or use an ObservableCollection

Comments