Xamarin forms Set Picker SelectedItem From List

Viewed 551

I am working with Xamarin.Forms and I am using Picker for a drop-down list.

I am trying to make a Picker display the book name that matches a string (for simplification purposes) from a ObservableCollection in a ViewModel.

PageOne.xaml:

<Picker x:Name="BookPicker" ItemDisplayBinding="{Binding Name}" ItemsSource="{Binding BookTypeList}"></Picker>

PageOne.cs:

public PageOne()
{
     InitializeComponent();
     this.BindingContext = new BookViewModel();

     string myBook = "c";

     for (int x = 0; x < 5; x++)
     {
          if (BookViewModel.BookTypeList[x].Name == myBook)
          {
               BookPicker.SelectedIndex = x;
          } 
     }
}

BookViewModel:

  public BookViewModel()
    {
        BookTypeList = new ObservableCollection<BookType>(){
            new BookType() { BookID = 0, Name = "a" },
            new BookType() { BookID = 1, Name = "b" },
            new BookType() { BookID = 2, Name = "c" },
            new BookType() { BookID = 3, Name = "d" },
            new BookType() { BookID = 4, Name = "e" },
        };
        bookType = BookTypeList[0];
    }

    public class BookType
    {
        public int BookID { get; set; }
        public string Name { get; set; }
    }

BookViewModel.BookTypeList results in this error:

CS0120: An object reference is required for the nonstatic field, method, or property

How can I iterate through the ObservableCollection in BookViewModel to find the ID that matches the string, so that I can set the Picker.SelectedIndex?

Thanks!

1 Answers

You got that error because BookViewModel is not a static class, if you are looking to access BookTypeList you need to do that thru a BookViewModel instance

public PageOne()
{
     InitializeComponent();
     this.BindingContext = new BookViewModel();

     string myBook = "c";
     var vm = BindingContext as BookViewModel;
     for (int x = 0; x < 5; x++)
     {
          if (vm.BookTypeList[x].Name == myBook)
          {
               BookPicker.SelectedIndex = x;
          } 
     }
}

Also if you have a unique item in the ObservableCollection, you may replace your For loop with FindIndex:

public PageOne()
{
     InitializeComponent();
     this.BindingContext = new BookViewModel();

     string myBook = "c";
     var vm = BindingContext as BookViewModel;
     BookPicker.SelectedIndex = vm.BookTypeList.FindIndex(x => x.Name.Equals(myBook));
}

Or SelectedItem instead of SelectedIndex

 BookPicker.SelectedItem = vm.BookTypeList.Find(x => x.Name.Equals(myBook));

If the item is not unique you may need to use Where clause/extension method from Linq

Related