Xamarin 表单从列表中设置选取器 SelectedItem

Xamarin forms Set Picker SelectedItem From List

我正在使用 Xamarin.Forms,我正在使用 Picker 作为下拉列表。

我正在尝试让选择器显示与 ViewModel 中的 ObservableCollection 中的字符串(出于简化目的)相匹配的书名。

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 导致此错误:

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

如何遍历 BookViewModel 中的 ObservableCollection 以找到与字符串匹配的 ID,以便我可以设置 Picker.SelectedIndex?

谢谢!

你得到那个错误是因为 BookViewModel 不是静态的 class,如果你想访问 BookTypeList 你需要通过 BookViewModel 实例

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;
          } 
     }
}

此外,如果您在 ObservableCollection 中有一个独特的项目,您可以将 For 循环替换为 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));
}

SelectedItem而不是SelectedIndex

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

如果该项目不是唯一的,您可能需要使用 Linq

中的 Where clause/extension 方法