Question

I want to shuffle a content in ObservableCollection,

public static ObservableCollection<whatsnewCompleteData> whatsnewCompleteList = new ObservableCollection<whatsnewCompleteData>();

 for (int i = 0; i < whatsnewfeed.feed.entry.Count; i++)
 {              
    whatsnewCompleteList.Add(new whatsnewCompleteData(i, content[i]);
 }

If it is normal list I can easily perform a shuffle! but observablecollection is directly bound to UI. Only thing I can do is using a random number each time while initializing. So here for the range of,

0 < whatsnewfeed.feed.entry.Count

How do I generate a random number and that covers all values from 0 to whatsnewfeed.feed.entry.count?

No correct solution

OTHER TIPS

First of all, you could shuffle the data of the ObservableCollection in-place, as you are suggesting, or you could create a new one, then overwrite the ObservableCollection.

Consider the case:

public static ObservableCollection<whatsnewCompleteData> whatsnewCompleteList = new ObservableCollection<whatsnewCompleteData>();

// A bindable property
public ObservableCollection<whatsnewCompleteData> WhatsNewCompleteList
{
    get
    {
        return whatsnewCompleteList;
    }
    set
    {
        whatsnewCompleteList = value;
        // Your property changed notifier method
        OnPropertyChanged("WhatsNewCompleteList");
    }
}

In your method:

// content should obviously be whatever object type you need to get
// (or already have)
public void Shuffle(List<object> content)
{
    // Note: you don't have to initialize an observable collection like this.
    // You can also create a list, shuffle it as you would normally, then call
    // new ObservableCollection<whatsnewCompleteData(shuffledList);
    var newWhatsnewCompleteList = new ObservableCollection<whatsnewCompleteData>();

    for (int i = 0; i < whatsnewfeed.feed.entry.Count; i++)
    {              
        newWhatsnewCompleteList.Add(new whatsnewCompleteData(i, content[i]);
    }
    WhatsNewCompleteList = newWhatsnewCompleteList;
}

This will overwrite the current list and update your bindings without having to worry about the UI freaking out.

The other option is to simply create a new list of values, then call Clear() on your static collection and fill it with the new values.

Hope this helps and happy coding!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top