WPF Datagrid: Lazy Loading / Inifinite scroll

2020-06-03 05:46发布

问题:

I fill the Datagrid with 250 rows. When the user scrolls down using the scrollbar (below 75% for example), I want to fetch the next 250 rows from the database, and so on. The idea is that the grid could have millions of results and we don't want to load them all, until the user requests them. Is there an existing mechanism for this?

EDIT: Because there seem to be a lot of confusion: I'm not looking for the standard data virtualization solutions, I already use them. But they all require you to specify the number of 'virtual rows' in advance, and that query is to costly for me. The reason why they require it is because it's makes it so much easier to calculate the current page/offset/etc when you know the total items in the grid. But it is a very costly sql-query to calculate that amount, so I want to migrate to another solution where I can skip the COUNT() query.

回答1:

So looks like Virtualization property of DataGrid wouldn't help you because it requires a full data set to be in the ItemsSource.

So to have in place a data lazy loading (See an article Data Virtualization) You can handle ScrollViewer.ScrollChanged event and apply a classical server-side paging approach. Basically you have to define and calculate such sings like Page Size, Page Number, Sort Order in this way you can request from a data base a required data set and show it on UI. Each time when Current Page Number or Sort Order is changing you need to request a data and update ItemsSource of the grid, also perhaps you need to restore Scroll Position as well but I'm not sure in this.

  • Calculate number of visible items
  • Do a data request to database usign parametrized query with parameters like PageNumber, PagiSize
  • Update DataGrid ItemsSource by a just loaded data items

I believe a main challenge would be to calculate a value of Page Size, Current Page Number. I believe Logical Scrolling mode would help you in this.



回答2:

Set DataGrid's EnableRowVirtualization property to true

Rows will therefore be loaded when user scrolls, so only the visible rows will actually be loaded