【问题标题】:Xamarin forms Set Picker SelectedItem From ListXamarin 表单从列表中设置选择器 SelectedItem
【发布时间】:2021-02-21 11:22:32
【问题描述】:

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

我正在尝试让 Picker 显示与 ObservableCollection 中的 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 导致此错误:

CS0120:非静态字段、方法或属性需要对象引用

如何遍历BookViewModel中的ObservableCollection,找到匹配字符串的ID,从而设置Picker.SelectedIndex?

谢谢!

【问题讨论】:

    标签: c# xamarin xamarin.forms viewmodel observablecollection


    【解决方案1】:

    您收到该错误是因为BookViewModel 不是静态类,如果您要访问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));
    

    如果项目不是唯一的,您可能需要使用来自LinqWhere 子句/扩展方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      相关资源
      最近更新 更多