【问题标题】:How To bind Limit Record in DataGrid UWP?如何在 DataGrid UWP 中绑定限制记录?
【发布时间】:2016-12-01 01:21:18
【问题描述】:

我们将如何在数据网格中进行此绑定,我有 30 条记录,但我只想绑定 10 条记录。我将所有值都用于 c# 中的集合列表类。谢谢

【问题讨论】:

    标签: wpf data-binding uwp uwp-xaml


    【解决方案1】:

    使用 Linq。例如:

    List<Product> datasource = db.TakeAllProducts();
    List<Product> first10 = datasource.Take(10).ToList();
    this.datagrid.DataSource = first10;
    

    【讨论】:

    • 嗨,非常感谢,现在我在 DataGrid 中只绑定了 10 条记录,为您提供帮助,祝您有美好的一天
    • 但是当我点击下一步按钮时没有前进 10 条记录仍然是绑定退出 10 条记录只是不移动到另一条记录?
    • 嗯好的,你需要分页
    【解决方案2】:

    要实现分页,可以按照以下步骤进行:

    1. 在您的页面中全局定义三个变量:

      //define how many pages totally accroding to calculation.
      int pageCount;
      //define current page number.
      int currentPage;
      //define how many items you want to show in page.
      int countPerPage;
      
    2. 在页面加载期间启动它们:

      protected override void OnNavigatedTo(NavigationEventArgs e)
      {
          countPerPage = 10;
          float tmpFloat = (float)myList.Count / countPerPage;
          pageCount = (int)Math.Ceiling(tmpFloat);
          currentPage = 1;
          ManageButton();//manage the buttons' disable
          myDataGrid.ItemsSource = myList.GetRange(0, countPerPage);
          ...
      }
      
    3. 通过以下方法计算显示哪些项目(我使用List.GetRange获取列表):

      private List<String> GetList(List<String> sourceList)
      {
          int index = (currentPage - 1) * countPerPage;
          int countsToShow;
          if (currentPage == pageCount)
          {
              countsToShow = myList.Count - (currentPage - 1) * countPerPage;
          }
          else
          {
              countsToShow = countPerPage;
          }
          return sourceList.GetRange(index, countsToShow);
      }
      
    4. 在您的上一个按钮或下一个按钮的单击事件中,处理数据网格的项目刷新。另外不要忘记在当前页面到达边界时启用或禁用按钮(通过 ManageButton 方法)。

      private void btnPrevious_Click(object sender, RoutedEventArgs e)
      {
          currentPage--;
          ManageButton();
          myDataGrid.ItemsSource = GetList(myList);
      }
      
      private void btnNext_Click(object sender, RoutedEventArgs e)
      {
          currentPage++;
          ManageButton();
          myDataGrid.ItemsSource = GetList(myList);
      }
      
      private void ManageButton()
      {
          if (currentPage <= 1)
          {
              btnPrevious.IsEnabled = false;
              btnNext.IsEnabled = true;
          }
          else if (currentPage >= pageCount)
          {
              btnPrevious.IsEnabled = true;
              btnNext.IsEnabled = false;
          }
          else
          {
              btnPrevious.IsEnabled = true;
              btnNext.IsEnabled = true;
          }
      }
      

    这是我的完整演示:Pagination

    【讨论】:

    • 非常感谢你有美好的一天:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2021-12-22
    • 2014-02-02
    • 2014-09-12
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    相关资源
    最近更新 更多