Search code examples
objectxamarinxamarin.formstelerikobservablecollection

How do I get an object from an observable item Collection by index?


I need to get the object in an observable collection by index to access a property of the item at that index.

This is a snippet of the code:

public ObservableCollection<TipsModel> TipObjects;
  private void LoadContent()
        {
            TipObjects = new ObservableCollection<TipsModel>();

            for (int i = 0; i < 5; i++)
            {
                TipsModel item = new TipsModel()
                {
                    Image = ImageSource.FromFile("nonindustryIcon.png"),
                    Title = "Kill energy vampires and save up to $100 a year",
                    Text = "Seventy-five percentof the electrical use by home electronics occurs when they're at home. \n People not at home means no electricity. Do not stay at home. Go stay on the streets. ",

                };
                TipObjects.Add(item);
            }
            foreach (TipsModel item in TipObjects)
            {
                img = item.Image;
                tipTitle = item.Title;
                tip = item.Text;
                item.Content = CreateContent();              
            }

            slideView.ItemsSource = TipObjects;
        }

  private void slideView_SlidedToIndex(object sender, Telerik.XamarinForms.Primitives.SlideView.SlideViewSlidedToIndexEventArgs e)
        {

            var slideId = slideView.Id;
            //TipsModel tip = TipObjects.item at index[18];

        }

Solution

  • You can just normally do

    var tip = TipObjects[18];
    

    Observable collection is just a normal, fully functional collection that supports indexing.

    Alternatively you can use the Items property as well. Both approaches are equivalent:

    var tip = TipObjects.Items[18];