Search code examples
c#windows-phone-8observablecollectionlonglistselector

c# update ObservableCollection in socket


I need to update myobservableCollection when i listen on a socket. Then sort myobservableCollection from largest to smallest. I 'm listening everytime for any update to do. This works fine.

But when i scroll down on my longListSelector, **every-time an update is done, i can' t reach the end of it, it returns me to the top.* * how to update it and be able to scroll down.

mySock.On("player:new-vote", (data) = > {
string newVoteData = data.ToString();
JObject obj = JObject.Parse(newVoteData);
string objId = (string) obj["id"];
int objStand = (int) obj["details"]["standing"];
int objUp = (int) obj["details"]["upVotes"];
int objDown = (int) obj["details"]["downVotes"];
string objBy = (string) obj["details"]["by"];
PlayerVotes newVote = new PlayerVotes() {
    by = objBy,
    _id = objId,
    downVotes = objDown,
    upVotes = objUp,
    standing = objStand
};
Deployment.Current.Dispatcher.BeginInvoke(() = > {
    var updateVoteSong = playerCollection.FirstOrDefault(x = > x._id == objId);
    updateVoteSong.votes = newVote;
    playerCollection = new ObservableCollection < PlayerSong > (playerCollection
        .OrderByDescending(x = > x.votes.standing));
    MainLongListSelector.ItemsSource = playerCollection;
});

});


Solution

  • First of all, you should not override your ObservableCollection everytime, the containing data changes.

    Rather use this extension to sort for example:

    public static class ObservableCollection
     {
          public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector)
          {
              List<TSource> sortedList = source.OrderByDescending(keySelector).ToList();
              source.Clear();
              foreach (var sortedItem in sortedList)
              {
                  source.Add(sortedItem);
              }
         }
     }
    

    If you override the Collection everytime, the bound control might receive heavy binding issues because they are never unbound.

    And to scroll to an specific element you can this:

    var lastMessage = playerCollection.LastOrDefault();
    MainLongListSelector.ScrollTo(lastMessage);
    

    This might not give you an 100% fitting answer, but it should push you in the right direction