0
votes

How to select item with index in ListView(Xamarin Forms)? I try this

ObservableCollection<TabItem> _tabs = new ObservableCollection<TabItem>();
_tabs.Add(new TabItem { Title = "Tab item" });
_tabs.Add(new TabItem { Title = "Tab item" });
_tabs.Add(new TabItem { Title = "Tab item" });

int selector = _tabs.Count;
ListView.SelectedItem = _tabs[selector];

But it doesn't work. Help me please.

Thank you! Best wishes.

2
what is the ListView's ItemsSource?Jason
` ObservableCollection<TabItem> _tabs = new ObservableCollection<TabItem>(); `Win Soft
what do you expect to happen when you manually set the SelectedItem?Jason
I resolve this issueWin Soft
You can mark the answer which would help more people with same problem.nevermore

2 Answers

0
votes
ObservableCollection<TabItem> _tabs = new ObservableCollection<TabItem>();
_tabs.Add(new TabItem { Title = "Tab item" });
_tabs.Add(new TabItem { Title = "Tab item" });
_tabs.Add(new TabItem { Title = "Tab item" });

int selector = _tabs.Count - 1;
ListView.SelectedItem = _tabs[selector];
0
votes

After adding 3 items to your collection, you end up with indices 0, 1, and 2 being populated.

Those are the only 3 numbers that you can use to access the collection at that point, so setting selector to Count property (which returns 3 after adding 3 items) results in trying to access element with index 3, which doesn't exist.

When working with collections, the last element you can access is always Count - 1 (unless it's empty).