【问题标题】:How to bind data from a List<class> to Picker element in Xamarin如何将 List<class> 中的数据绑定到 Xamarin 中的 Picker 元素
【发布时间】:2022-08-15 16:00:53
【问题描述】:

我有一个从 API 获取数据的列表 (List&lt;Customer&gt; l_Customer)。 &lt;Customer&gt; 类包括fullname,它是字符串值。我怎样才能只从该列表中获取全名并将它们显示在 Picker 的下拉列表中?

    标签: c# list xamarin drop-down-menu picker


    【解决方案1】:

    我用 MVVM 做一个简单的例子供你参考。

    xml:

      <Picker ItemsSource="{Binding l_Customer}" ItemDisplayBinding="{Binding fullname}"></Picker>
    

    后面的代码:

    public partial class Page14 : ContentPage
    {
        public Page14()
        {
            InitializeComponent();
            this.BindingContext = new CustomerViewModel();
        }
    }
    public class CustomerViewModel
    {
        public List<Customer> l_Customer { get; set; }
        public CustomerViewModel()
        {
            l_Customer = new List<Customer>()
            {
                new Customer(){ fullname="A"},
                new Customer(){ fullname="B"},
                new Customer(){ fullname="C"},
            };
        }
    }
    public class Customer
    {
        public string fullname { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      在文档中有一个 example 可以做到这一点

      <Picker Title="Select a customer"
          ItemsSource="{Binding l_Customer}"
          ItemDisplayBinding="{Binding fullname}" />
      

      或在代码中

      var picker = new Picker { Title = "Select a Customer" };
      picker.SetBinding(Picker.ItemsSourceProperty, "l_Customer");
      picker.ItemDisplayBinding = new Binding("fullname");
      

      【讨论】:

      • 创建视图模型是一种有用的方法吗?为了将值绑定到视图模型中的选择器,它是否还需要是带有new ObservableCollection&lt;Customer&gt; 的 IList<>?
      【解决方案3】:

      这种方法对我不起作用,我不知道为什么。

      我有一个 ViewModel (SettingsViewModel) 和一个 Model (Settings)

      设置视图模型

      [可观察属性] 私人列表设置;

      但我无法在绑定中引用设置的属性。

      <Picker ItemSource={绑定设置} ItemDisplayBinding={绑定姓名} />

      绑定到名称不起作用

      【讨论】:

        猜你喜欢
        • 2015-05-11
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 2013-04-12
        • 2020-05-20
        • 2020-02-18
        • 1970-01-01
        • 2019-03-15
        相关资源
        最近更新 更多