【问题标题】:Shuffling while initializing a Observable Collection初始化 Observable 集合时的洗牌
【发布时间】:2014-03-04 18:17:55
【问题描述】:

我想打乱 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 的所有值?

【问题讨论】:

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


    【解决方案1】:

    首先,您可以按照您的建议将ObservableCollection 的数据就地洗牌,或者您可以创建一个新数据,然后覆盖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;
    }
    

    这将覆盖当前列表并更新您的绑定,而不必担心 UI 崩溃。

    另一种选择是简单地创建一个新的值列表,然后在您的 static 集合上调用 Clear() 并用新值填充它。

    希望这对编码有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2013-11-30
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2018-10-05
      • 1970-01-01
      相关资源
      最近更新 更多