简体   繁体   English

Xamarin Forms - 如何显示绑定的数据(来自 HttpClient 的列表)?

[英]Xamarin Forms - How to display data binded (List from HttpClient)?

Can't display data in list view after json deserialization. json 反序列化后无法在列表视图中显示数据。 How do i need to set it up in order to see it?我需要如何设置才能看到它?

I'm data binding my reponse from http client using binding context so i can use it in my list view.我正在使用绑定上下文从 http 客户端对我的响应进行数据绑定,因此我可以在我的列表视图中使用它。

MainPage.xaml主页.xaml

<ContentPage
        Title="Home"
     >
        <Grid>
            <ListView ItemsSource="{Binding .}">
            <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout>
                            <Label Text="{Binding Description}"/>
                            <Label Text="{Binding Value}"/>
                        </StackLayout>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </ContentPage>

MainPage.cs主页.cs

public MainPage()
        {
            DataService ds = new DataService();

            BindingContext = ds.GetBillsAsync();

            InitializeComponent();

            Chart1.Chart = new BarChart { Entries = entries, LabelTextSize = (float)Convert.ToDouble(Device.GetNamedSize(NamedSize.Large, typeof(Label))), BackgroundColor = SKColors.Transparent };



        }

DataService.cs数据服务.cs

public class DataService
    {
        HttpClient client = new HttpClient();

        public async Task<List<Bill>> GetBillsAsync()
        {
            try
            {
                string url = "my url";

                var response = await client.GetStringAsync(url).ConfigureAwait(continueOnCapturedContext: false); ;
                var bills = JsonConvert.DeserializeObject<List<Bill>>(response);
                return bills;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }

I'm not getting any error messages, except for this output message "Binding: System.Threading.Tasks.Task`1[System.Collections.Generic.List`1[Test.Models.Bill]] can not be converted to type 'System.Collections.IEnumerable'" which i don't think it is the problem since i can see my list being populated correctly when i'm debugging.我没有收到任何错误消息,除了此 output 消息"Binding: System.Threading.Tasks.Task`1[System.Collections.Generic.List`1[Test.Models.Bill]] can not be converted to type 'System.Collections.IEnumerable'"我认为这不是问题,因为我在调试时可以看到我的列表被正确填充。

Can you help me please?你能帮我吗?

Thank you in advance先感谢您

Nikhil's method is one way,if you only want to set the List which request from http client to the listview,you could binding to the ListView's ItemsSource property. Nikhil 的方法是一种方法,如果您只想将来自 http 客户端的请求的列表设置到列表视图,您可以绑定到列表视图的ItemsSource属性。

in the MainPage.xaml.cs :MainPage.xaml.cs 中

public partial class MainPage: ContentPage
{
   DataService ds = new DataService();
   public MainPage()
    {

        InitializeComponent();
        Chart1.Chart = new BarChart { Entries = entries, LabelTextSize = (float)Convert.ToDouble(Device.GetNamedSize(NamedSize.Large, typeof(Label))), BackgroundColor = SKColors.Transparent };
    }

   protected override async void OnAppearing()
    {
        base.OnAppearing();
        listview.ItemsSource = await ds.GetBillsAsync();
    }
}

in MianPage.xaml :MianPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         Title="Home"
         x:Class="App18.MainPage">
  <ContentPage.Content>
    <StackLayout>
        <ListView x:Name="listview">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Label Text="{Binding Description}"/>
                        <Label Text="{Binding Value}"/>
                    </StackLayout>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
 </ContentPage.Content>
</ContentPage>

You need to change the GetBillsAsync Method to retrieve the Array and then convert into List using Array.ToList() with System.Linq.您需要更改 GetBillsAsync 方法以检索 Array,然后使用 Array.ToList() 和 System.Linq 转换为 List。

You need to implement a ViewModel for this.您需要为此实现一个 ViewModel。 You can use the NuGet MVVM helpers for the BaseViewModel or implement your own.您可以将 NuGet MVVM 帮助程序用于 BaseViewModel 或实现您自己的。

using System.Windows.Input;
using MvvmHelpers.Interfaces;

namespace NameSpace.ViewModel
{
    public partial class HomeViewModel : BaseViewModel
    {

        private ObservableCollection<Bill> _listOfbills = new ObservableCollection<Bill>();
        public ObservableCollection<Bill> ListOfbills
        {
            get => _listOfbills;
            set => SetProperty(ref _listOfbills, value);
        }
        public HomeViewModel()
        {
            DataService ds = new DataService();
            ListOfbills = ds.GetBillsAsync()
        }
    }
}

Then your MainPage becomes:-然后您的 MainPage 变为:-

HomeViewModel vm; HomeViewModel 虚拟机; public MainPage() {公共主页(){

            BindingContext = vm = new HomeViewModel();

            InitializeComponent();

            Chart1.Chart = new BarChart { Entries = entries, LabelTextSize = (float)Convert.ToDouble(Device.GetNamedSize(NamedSize.Large, typeof(Label))), BackgroundColor = SKColors.Transparent };



        }

Then in the Xaml you can change this line as follows:-然后在 Xaml 你可以改变这一行如下: -

<ListView ItemsSource="{Binding ListOfbills}">

These changes should work.这些更改应该有效。 Let me know if you face difficulties.如果您遇到困难,请告诉我。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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