开发者

how to populate the itemssource while scrolling

I would like t开发者_高级运维o retrieve data from my WCF service as the user is scrolling over a datagrid. What are some options for accomplishing this, particularly those that would favour following the mvvm pattern.


If anybody is still looking for this, here is one way to implement it in Silverlight and MVVM Light. Other methods are possible, like tapping into the vertical scroll bar position, but I believe it is not accessible in SL without a custom control.

In the DataGrid LoadingRow event, check if the current row is close to the bottom of the databound itemssource. Then send a Message to the ViewModel to start fetching the next group of rows. The registered event in the ViewModel adds to the databound property.

Here is a simplified code sample.

In code behind:

void dg_LoadingRow(object sender, DataGridRowEventArgs e)
{
  ObservableCollection<YourDataType> list = dg.ItemsSource as ObservableCollection<YourDataType>;
  int idx = list.IndexOf((YourDataType)e.Row.DataContext);
  if ((list.Count() - idx) == 5)  //start fetching when loading 5th from bottom of current list
  {
    Messenger.Default.Send(null, "fetchdatatoken");
  }
}

In the ViewModel, implement something like this:

 Messenger.Default.Register(this, "fetchdatatoken", () =>
 {
   var returnedList = webservice.getdata( chunkNumber, chunkSize, "any additional parameters you need for your query" )
   yourListProperty.AddRange(returnedList);  //yourListProperty is the databound ObservableCollection property    
 }

Additional items you should code for:

  • add bounds checking
  • If your chunk size is too small then you might want to handle the initial load special case.
  • be careful about the load it generates on the database server
  • make your web service access efficient. For example in Linq use Skip() and Take()
  • prevent multiple concurrent service calls
  • be careful about memory use on the client side, handle the UnloadingRow event to free up memory if your list is large
  • anything else I might be missing


I've just published some blog posts and a sample which implement "stealth paging" whilst a user is scrolling through a Datagrid. I'm a great MVVM fan so, naturally, my solution fits well with that approach. See this answer for details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜