开发者

OnPropertyChanged with a List

开发者 https://www.devze.com 2023-01-18 06:59 出处:网络
I have a data grid in a view that is bound to a List in a viewmodel.I have a lot of data to retrieve for the list, so I want to break it up into many small retrievals instead of one big one.

I have a data grid in a view that is bound to a List in a viewmodel. I have a lot of data to retrieve for the list, so I want to break it up into many small retrievals instead of one big one.

I want this to happen on a background thread with the UI updating (the grid binding the new data) at the end of each batch retrieved.

At the end of each retrieval, I am doing a List.AddRange() on the private backer, then raising the OnPropertyChanged event passing the name of the public property that the grid is bound to.

Initially I tried this with 6 iterations that retrieve 100 items each. When running in the background, the UI would update after the first 100, but then not update the last 500 (even though the data was successfully added to the underlying list in the viewmodel).

Thinking that I had some issues with marshalling to the UI thread, I ran开发者_如何转开发 it sychroneously, expecting it to either work as expected (albeit blocking the UI during each retrieval) or block the UI during all the retrievals - but in either case, updating at the end to show 600 items. However, it ends up doing the same thing as when I run it in the background - only updates the first 100 and not the rest.

Below is the method I am using with both attempts, the top half being the background version commented out.

What am I doing wrong?

public void StartDataStream()
{
    //Task<List<Car>> task = _taskFactory.StartNew(this._retrieveData);

    //task.ContinueWith(t =>
    //{
    //    if (this._cars == null) this._cars = new List<Car>();

    //    this._cars.AddRange(t.Result);
    //    base.OnPropertyChanged("Cars");

    //    this.iterations += 1;
    //    if (iterations < 6) StartDataStream();
    //});

    if (this._cars == null) this._cars = new List<Car>();

    this._cars.AddRange(this.GetCarList(eq,s,e));
    base.OnPropertyChanged("Cars");

    this.iterations += 1;

    if (iterations < 6) StartDataStream();
}


Have you tried using an ObservableCollection<T> rather than a List<T>

I assume you have a public property called Cars similar to...

public List<Car> Cars{

   get { return this._cars;}
   set
   {
      this._cars = value;
      base.OnPropertyChanged("Cars");
   }

}

If not this will not actually do anything...base.OnPropertyChanged("Cars");

Extension Method AddRange for ObservableCollection

public static class Extensions
{
    public static void AddRange(this ObservableCollection obj, List<T> items)
    {
        foreach (var item in items)
          obj.Add(item);
    }
}
0

精彩评论

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