使用REST API的Xamarin中的显示列表

时间:2018-08-28 03:58:11

标签: c# listview xamarin mvvm xamarin.forms

我想显示使用API​​的Xamarin(VS 2017)中的产品列表,但是在运行我的应用程序时,它向我显示了一个空列表(如图所示)

Screenshot

对于上述情况,我通过POSTMAN验证了该服务可以使用

POSTMAN

然后我创建一个名为ApiServices的服务,该服务使用API​​:

APISERVICE.CS:

public async Task<Response> GetList<T>(string urlBase, string servicePrefix, string controller)
        {
            try
            {
                var client = new HttpClient();          
                client.BaseAddress = new Uri(urlBase);
                var url = string.Format("{0}{1}", servicePrefix, controller);
                var response = await client.GetAsync(url);
                var result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return new Response
                    {
                        IsSuccess = false,
                        Message = result,
                    };
                }

                var list = JsonConvert.DeserializeObject<List<T>>(result);

                return new Response
                {
                    IsSuccess = true,
                    Message = "Ok",
                    Result = list,
                };
            }
            catch (Exception ex)
            {
                return new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                };
            }
        }

然后,在我的ProductsViewModel中,我调用GetList方法并传递参数:

PRODUCTOSVIEWMODEL.CS:

public ObservableCollection<Product> Productos { get { return this.productos;  }
                                                           set { this.SetValue(ref this.productos, value); }
                                                         }    
        private ObservableCollection<Product> productos;    
        private ApiService apiService;

        public ProductosViewModel()
        {
            this.apiService = new ApiService();
            this.LoadProductos();
        }

        private async void LoadProductos()
        {
            var response = await this.apiService.GetList<Product>("https://salesapiservices.azurewebsites.net", "/api", "/Products");

            if (!response.IsSuccess)
            {
                await Application.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar");
                return;
            }

            var list = (List<Product>)response.Result;              
            Productos = new ObservableCollection<Product>(list);
        }

最后,在我看来,我展示了我想要的元素:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Fundamentos.Views.ProductosPage"
             BindingContext="{Binding Main, Source={StaticResource Locator}}"
             Title="Productos">

    <ContentPage.Content>
        <StackLayout
            BindingContext="{Binding Productos}"
            Padding="4">

            <ListView 
                ItemsSource="{Binding Productos}">                    
            </ListView>

        </StackLayout>
    </ContentPage.Content>

</ContentPage>

我附上我的产品型号:

public class Product
    {
        public int ProductId { get; set; }

        public string Description { get; set; }

        public string Remarks { get; set; }

        public string ImagePath { get; set; }

        public Decimal Price { get; set; }

        public bool IsAvailable { get; set; }

        public DateTime PublishOn { get; set; }

        public string ImageFullPath
        {
            get
            {
                if (string.IsNullOrEmpty(this.ImagePath))
                {
                    return "noproduct";
                }

                return $"https://salesbackend.azurewebsites.net/{this.ImagePath.Substring(1)}";
            }

        }

        public override string ToString()
        {
            return this.Description;
        }
    }

我验证JSON是否到达:

JSON

值得一提的是,我正在使用MVVM模式,并且已经在MainViewModel中实例化了ProductsViewModel类,并且已经检查了代码,但找不到错误!

对我有什么帮助吗?请随时关注您的评论

1 个答案:

答案 0 :(得分:1)

由于要绑定到ListView的模型是复杂类型,因此需要为ListView定义自定义布局

您可以参考以下代码:

<ListView ItemsSource="{Binding Productos}"> 
<ListView.ItemTemplate>
   <DataTemplate>
      <ViewCell>
              <Label Text="{Binding Description}"
                FontSize="Large" 
                FontAttributes="Bold" 
                HorizontalTextAlignment="Start"
                Margin="20,0,0,0"
                VerticalTextAlignment="Center"
                >
    </ViewCell>
  </DataTemplate>
</ListView.ItemTemplate>
</ListView>