Reputation: 16900
I have Listbox whose item panel is set to wrappanel. I want that whenever a new item is added to listbox my collection should be sorted and the process should be visible on the UI. I mean the user should be able to see that fancy effect to help them identify that the item is being sorted. I looked at few posts on stackoverflow and they suggest to use CollectionViewSource. However my itemsource is bound to ObservableCollection in ViewModel.
First I wrote this code. It works however as a new collection is bound I can't see that fancy effect where the items in the container just move to their new position from the original position :-
var photoList = PhotosToUpload.ToList<Photo>();
photoList.Sort(new PhotoSorter());
PhotosToUpload = new ObservableCollection<Photo>(photoList);
This is my class :-
public class PhotoSorter : IComparer<Photo>
{
public int Compare(Photo x, Photo y)
{
return x.PhotoByteArr.Length - x.PhotoByteArr.Length;
}
}
Then I wrote a simple bubble sorting algorithm. This achives the desired effect but I don't know why it takes too long time. I know it's the most ineffecient algorithm that anybody can think of but still sorting 10 items shouldn't take more than a second. Here it takes 4-5 seconds.
for (int i = 0; i < PhotosToUpload.Count; i++)
{
for (int j = 0; j < PhotosToUpload.Count - 1 - i; j++)
{
if (PhotosToUpload[j].PhotoByteArr.Length > PhotosToUpload[j + 1].PhotoByteArr.Length)
{
Photo photo = PhotosToUpload[j];
PhotosToUpload[j] = PhotosToUpload[j + 1];
PhotosToUpload[j + 1] = photo;
}
}
}
Can anybody tell me what's the best I can do at this point of time? and why is bubble sorting taking so long even with just 10 items?
Upvotes: 3
Views: 336
Reputation: 163
To check for changes, use the CollectionChanged
event.
You have an error in your comparer:
return x.PhotoByteArr.Length - y.PhotoByteArr.Length;
btw. your code executes instantly for me... Maybe the problem is in your Photo class? Or your binding/events?
Is Photo.PhotoByteArr
a calculated value?
Upvotes: 1