Question

Hi I have a ObservableCollection getting data in every minute. When it reaches an hour, I would like to clear the first item and move all the items up then adding the new item, thus maintaining it at 60 elements. Does anyone have any idea how to do so?

Here is my code:

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;
    }
}
Was it helpful?

Solution

Just count the items in your list and remove the top item if the count equals 60. Then insert the new item like normal.

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

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

Also if you Bind your ItemsSource instead of setting it, it will update automatically when the collection changes.

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