2011-10-13 46 views
0

嗨我有一個ObservableCollection可以在每分鐘內獲取數據。達到一小時後,我想清除第一個項目,然後移動所有項目,然後添加新項目,從而將它保持在60個元素。有誰知道如何去做?在可觀察的集合中維護60個元素

這裏是我的代碼:

public class MainWindow : Window 
{    
    double i = 0; 
    double SolarCellPower = 0; 
    DispatcherTimer timer = new DispatcherTimer(); 
    ObservableCollection<KeyValuePair<double, double>> Power = new ObservableCollection<KeyValuePair<double, double>>(); 

    public MainWindow() 
    { 
     InitializeComponent(); 

     timer.Interval = new TimeSpan(0, 0, 1); // per 5 seconds, you could change it 
     timer.Tick += new EventHandler(timer_Tick); 
     timer.IsEnabled = true; 
    } 

    void timer_Tick(object sender, EventArgs e) 
    { 
     SolarCellPower = double.Parse(textBox18.Text); 
     Power.Add(new KeyValuePair<double, double>(i, SolarCellPower)); 
     i += 5; 
     Solar.ItemsSource = Power; 
    } 
} 

回答

1

只是計數清單中的項目,如果計數等於60.然後插入像正常的新項目中刪除頂部的項目。

if (Power.Count == 60) 
    Power.RemoveAt(0); 

Power.Add(new KeyValuePair<double, double>(i, SolarCellPower)); 

此外,如果您綁定您的ItemsSource而不是設置它,它會在集合更改時自動更新。