Xamarin 选择器不显示列表中的日期

Xamarin picker not showing the date from the list

我有以下代码:

    <ContentPage.BindingContext>
        <local:PisterosViewModel/>
    </ContentPage.BindingContext>

<Picker x:Name="pck_Pisteros"
                        ItemDisplayBinding="{Binding PisteroN}"
                        ItemsSource="{Binding PisterosLista}"
                        SelectedItem="{Binding PisterosLista}"
                        Title="Seleccione el usuario..."/>

然后我的模型:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Text;

namespace ServLottery.Models
{
    public class Pisteros
    {
        public string PisteroID { get; set; }
        public string PisteroN { get; set; }

    }

}

和视图模型:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace ServLottery.Models
{
    public class PisterosViewModel
    {
        public IList<Pisteros> PisterosLista { get; set; }

        public PisterosViewModel()
        {
            try
            {
                PisterosLista = new ObservableCollection<Pisteros>();
                GetPisteros();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private async void GetPisteros()
        {
            try
            {
                RestClient client = new RestClient();
                var pist = await client.Get<Models.Pisteros>("https://servicentroapi.azurewebsites.net/api/Pisteros");
                if (pist != null)
                {
                    PisterosLista = pist;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

    }
}

我在 var pist 中设置了一个断点,它确实有值,然后 Pisteros list 似乎也得到了值,这是在页面加载时执行的,所以我不明白是什么问题,但是选择器从不显示选项。

欢迎来到 SO!

Xaml中的BindingContext似乎无法处理动态数据,例如来自网络服务器的API数据。

有一个变通方法通过在 ContentPage 中使用编码动态绑定 ItemSource ,也可以参考 this officail sample

因此,在Page.Xaml.cs中添加代码如下:

protected override async void OnAppearing()
{
    pck_Pisteros.ItemsSource = await GetTasksAsync();
    base.OnAppearing();
}

private async Task<List<Pisteros>> GetTasksAsync()
{
    List<Pisteros> PisterosLista = new List<Pisteros>();
    HttpClient client = new HttpClient();
    Uri uri = new Uri(string.Format("https://servicentroapi.azurewebsites.net/api/Pisteros", string.Empty));
    HttpResponseMessage response = await client.GetAsync(uri);
    if (response.IsSuccessStatusCode)
    {
        string content = await response.Content.ReadAsStringAsync();
        PisterosLista = JsonConvert.DeserializeObject<List<Pisteros>>(content);
        Console.WriteLine("content :: " + content);
        Console.WriteLine("Data :: " + PisterosLista);
    }

    return PisterosLista;
}

现在会显示: