SunnySonic
SunnySonic

Reputation: 1326

Index of Observablecollection and listview xamarin forms

Desperately trying to get the index of a listview which is fed by an observable collection from a separate viewmodel class.

in my mainpage, which holds the listview xaml(called "mainlist") i have the onitemselected method which needs to give me the index.

I've tried all so far without any luck.

This is the only code that applies but it gives me null reference expception as well:

            int index = (mainlist.ItemsSource as List<MainListItem>).IndexOf(e.SelectedItem as MainListItem);

Saying Object reference not set to an instance of an object.

What am i missing here?

This is my mainviewmodel.cs that creates the observablecollection

private ObservableCollection<MainListItem> _list;

        public ObservableCollection<MainListItem> List
        {
            get { return _list; }
            set
            {
                _list = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(List)));
            }
        }

Upvotes: 1

Views: 477

Answers (1)

SunnySonic
SunnySonic

Reputation: 1326

Eventually I solved it by looping through the whole list and calculating my own index like so below: I'm aware that there must be a better way, but since my list is relatively small, this serves me well.

int index = 0;
int i = 1;

foreach (MainListItem itemtocheck in mainlist.ItemsSource as ObservableCollection<MainListItem>)
                {
                    if(itemtocheck == e.SelectedItem)
                    {
                        index = i;
                        Debug.WriteLine("Index is " + index);
                        break;
                    }
                    else
                    {

                        Debug.WriteLine("No match for index at " + i);
                        i++;
                    }

                }

Upvotes: 1

Related Questions