简体   繁体   中英

Picker List in Xamarin Forms

I'm creating an app that should import a lis from a Rest Api that connects with an sql server

it is working perfect in postman

but in Xamarin Evrithing comes blank

here is my code

this is the repo

public Alamacenes[] getAlmacenes()
        {
            try
            {
                Alamacenes[] almacenes;
                var URLWebAPI = "https://www.avila.somee.com/ApiAlexa/api/Almacenes";
                using (var Client = new System.Net.Http.HttpClient())
                {
                    var JSON = Client.GetStringAsync(URLWebAPI);
                    almacenes = JsonConvert.DeserializeObject<Alamacenes[]>(JSON.Result);
                }

                return almacenes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

this is my codebehind

 protected async void OnAppearing()
        {
            Repositorio repo = new Repositorio();
            Alamacenes[] listalmacenes = repo.getAlmacenes();
            foreach (var item in listalmacenes)
            {
                base.OnAppearing();

                Almacen.Items.Add(item.CodigoAlmacen.ToString());
                Almacen.Items.IndexOf(item.Almacen.ToString());
            }
        }

and this image is the result

enter image description here

i would like to know if i'm doing something wrong with my code

I think you are setting the list to the picker while is empty, You should await the response and after that set the item source to the picker. Take a look on this quick sample.

//XAML Code
    <Picker x:Name="almacenPicker" ItemDisplayBinding="{Binding Almacen}" />

//Code behind code
    protected override async void OnAppearing()
    {
        base.OnAppearing();
        var almacenList = await GetAlamacenes();
        almacenPicker.ItemsSource = almacenList;
    }

    public Task<List<Almacene>> GetAlamacenes()
    {
        return GetAsync<List<Almacene>>("https://www.avila.somee.com/ApiAlexa/api/Almacenes");
    }

    public async Task<TResult> GetAsync<TResult>(string uri)
    {
        var httpClient = new HttpClient();

        HttpResponseMessage response = await httpClient.GetAsync(uri);

        var content = await response.Content.ReadAsStringAsync();

        return await Task.Run(() => JsonConvert.DeserializeObject<TResult>(content));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM