【问题标题】:Show List in Xamarin consuming REST API在使用 REST API 的 Xamarin 中显示列表
【发布时间】:2019-02-02 14:44:39
【问题描述】:

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

对于上述内容,我通过 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 是否到达:

值得一提的是,我占用了MVVM模式,并且在MainViewModel中实例化了ProductsViewModel类,我查看了代码也没有发现错误!

对我有什么帮助吗?请继续关注您的 cmets

【问题讨论】:

  • 返回新的响应 { };你的代码中的响应是什么?是类还是Httpresponsemessage?

标签: c# listview xamarin mvvm xamarin.forms


【解决方案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>

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 2018-12-17
    • 2021-04-10
    • 2015-07-19
    • 2019-07-03
    • 2022-01-25
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多