在初始化Observable Collection时进行洗牌

时间:2014-03-04 18:17:55

标签: c# windows-phone-8 windows-8 windows-phone windows-store-apps

我想在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]);
 }

如果是正常列表,我可以轻松进行随机播放!但是observablecollection直接绑定到UI。我唯一能做的就是每次初始化时都使用一个随机数。 所以这里的范围是

0 < whatsnewfeed.feed.entry.Count

如何生成随机数并涵盖从0到whatsnewfeed.feed.entry.count的所有值?

1 个答案:

答案 0 :(得分:0)

首先,您可以按照您的建议对就地ObservableCollection的数据进行随机播放,或者您可以创建一个新数据,然后覆盖{{1} }。

考虑这个案例:

ObservableCollection

在你的方法中:

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");
    }
}

这将覆盖当前列表并更新您的绑定,而不必担心用户界面会被吓坏。

另一种选择是简单地创建一个新的值列表,然后在// 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; } 集合上调用Clear()并使用新值填充它。

希望这有助于编码!