从json延迟加载gridview

问题描述 投票:0回答:1

我在gridview中有一个延迟加载,其数据来自JSON。

JSON示例:

{
    "error": false,
    "total_data": 32,
    "data_per_page": "16",
    "current_page": 1,
    "total_page": 2,
    "current_total": 16,
    "data": [
        {
            "id": "2613",
            "judul": "Kamus ID EN",
            "slug": "kamus-id-en",
            "cover": "https://mhnkp2.com/src/umum/cover/kamus_ID_EN-thumb.jpg",
            "path": "https://mhnkp2.com/school/dl/dodl/2613",
            "ukuran": "3504835",
            "formated_size": "3.34 MB",
            "fname": "kamus_ID_EN.pdf",
            "publish": "1",
            "urgent": "400",
            "kelas": "0",
            "nama_kelas": "Umum"
        },

XAML:

<Grid x:Name="content" Grid.Row="1" Loaded="MainGrid_Loaded">

            <GridView
                x:Name="itemGridView"
                Loaded="itemGridView_Loaded">

                <GridView.ItemTemplate>
                    <DataTemplate>
                        <Grid
                            Width="135"
                            Height="280"
                            Margin="5,5,5,5"
                            Background="White">
                                <TextBlock
                                    x:Name="title"
                                    Margin="0,0,10,10"
                                    FontSize="14"
                                    FontWeight="SemiBold"
                                    Foreground="Black"
                                    Style="{StaticResource TitleTextBlockStyle}"
                                    Text="{Binding Judul}"
                                    TextWrapping="Wrap" />
                        </Grid>
                    </DataTemplate>
                </GridView.ItemTemplate>
            </GridView>

代码:

ObservableCollection<Buku> datasource = new ObservableCollection<Buku>();
int offset = 0;
        private void MainGrid_Loaded(object sender, RoutedEventArgs e)
                    {
                        itemGridView.ItemsSource = datasource;
                        Umum(1);
                    } 
    public class Buku
        {
            public string Judul { get; set; }
        }

            private async void Umum(int offset)
            {
                urlPath = "https://mhnkp2.com/school/api-v3/fetch/umum";
                var httpClient = new HttpClient(new HttpClientHandler());
                var values = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("halaman", offset.ToString()),
                    new KeyValuePair<string, string>("limit", "16"),
                    new KeyValuePair<string, string>("SCH-API-KEY", "SCH_KEnaBiDeplebt")
                };

                var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
                response.EnsureSuccessStatusCode();
                string jsonText = await response.Content.ReadAsStringAsync();
                try
                {
                    double total = groupObject1["total_data"].GetNumber();
                    double pages = groupObject1["total_page"].GetNumber();
                    double page = groupObject1["current_page"].GetNumber();

                    Buku file = new Buku();
                    file.PageNo = Convert.ToInt32(page);
                    file.Pages = Convert.ToInt32(pages);
                    file.Total = Convert.ToInt32(total);
                    JsonArray jsonData1 = jsonObject["data"].GetArray();
                    foreach (JsonValue groupValue1 in jsonData1)
                    {
                        JsonObject groupObject2 = groupValue1.GetObject();
                        string title = groupObject2["judul"].GetString();

                        Buku file1 = new Buku();
                        file1.Judul = title;
                        datasource.Add(file1);
                    }
                    itemGridView.ItemsSource = datasource;
                }
            }

            private void itemGridView_Loaded(object sender, RoutedEventArgs e)
                    {
                        ScrollViewer viewer = GetScrollViewer(this.itemGridView);
                        viewer.ViewChanged += Viewer_ViewChanged;
                    }

                    private void Viewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
                    {
                        ScrollViewer view = (ScrollViewer)sender;
                        double progress = view.VerticalOffset / view.ScrollableHeight;
                        //Debug.WriteLine(progress);
                        if (progress > 0.7 && !incall && !endoflist)
                        {
                            incall = true;
                            busyindicator.IsActive = true;
                            Umum(++offset);
                        }
                    }

                    public static ScrollViewer GetScrollViewer(DependencyObject depObj)
                    {
                        if (depObj is ScrollViewer) return depObj as ScrollViewer;

                        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                        {
                            var child = VisualTreeHelper.GetChild(depObj, i);
                            var result = GetScrollViewer(child);
                            if (result != null) return result;
                        }
                        return null;
                    }

我有一个问题,gridview应该在第1页和第2页上显示数据,但是在gridview中,第2页上显示的数据是第1页上的数据的重复,如下所示:picture如何解决?

注意:

  • 页面使用“ offset”参数

  • 页面限制为JSON中的“ total_page”

c# json gridview uwp lazy-loading
1个回答
0
投票

您只需要将偏移量值传递给MainGrid_Loaded并将偏移量零设置为1

ObservableCollection<Buku> datasource = new ObservableCollection<Buku>();
int offset = 1; // set offset zero to one 
        private void MainGrid_Loaded(object sender, RoutedEventArgs e)
                    {
                        itemGridView.ItemsSource = datasource;
                        Umum(offset); // just change 1 to offset 
                    } 
    public class Buku
        {
            public string Judul { get; set; }
        }

            private async void Umum(int offset)
            {
                urlPath = "mhnkp2.com/school/api-v3/fetch/ktsp2006/kelas/1";
                var httpClient = new HttpClient(new HttpClientHandler());
                var values = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("halaman", offset.ToString()),
                    new KeyValuePair<string, string>("limit", "16"),
                    new KeyValuePair<string, string>("SCH-API-KEY", "SCH_KEnaBiDeplebt")
                };

                var response = await httpClient.PostAsync(urlPath, new FormUrlEncodedContent(values));
                response.EnsureSuccessStatusCode();
                string jsonText = await response.Content.ReadAsStringAsync();
                try
                {
                    double total = groupObject1["total_data"].GetNumber();
                    double pages = groupObject1["total_page"].GetNumber();
                    double page = groupObject1["current_page"].GetNumber();

                    Buku file = new Buku();
                    file.PageNo = Convert.ToInt32(page);
                    file.Pages = Convert.ToInt32(pages);
                    file.Total = Convert.ToInt32(total);
                    JsonArray jsonData1 = jsonObject["data"].GetArray();
                    foreach (JsonValue groupValue1 in jsonData1)
                    {
                        JsonObject groupObject2 = groupValue1.GetObject();
                        string title = groupObject2["judul"].GetString();

                        Buku file1 = new Buku();
                        file1.Judul = title;
                        datasource.Add(file1);
                    }
                    itemGridView.ItemsSource = datasource;
                }
            }

            private void itemGridView_Loaded(object sender, RoutedEventArgs e)
                    {
                        ScrollViewer viewer = GetScrollViewer(this.itemGridView);
                        viewer.ViewChanged += Viewer_ViewChanged;
                    }

                    private void Viewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
                    {
                        ScrollViewer view = (ScrollViewer)sender;
                        double progress = view.VerticalOffset / view.ScrollableHeight;
                        //Debug.WriteLine(progress);
                        if (progress > 0.7 && !incall && !endoflist)
                        {
                            incall = true;
                            busyindicator.IsActive = true;
                            Umum(offset++);
                        }
                    }

                    public static ScrollViewer GetScrollViewer(DependencyObject depObj)
                    {
                        if (depObj is ScrollViewer) return depObj as ScrollViewer;

                        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                        {
                            var child = VisualTreeHelper.GetChild(depObj, i);
                            var result = GetScrollViewer(child);
                            if (result != null) return result;
                        }
                        return null;
                    }
© www.soinside.com 2019 - 2024. All rights reserved.