在一个可观察集合中维护60个元素

本文关键字:集合 维护 60个 元素 观察 一个 | 更新日期: 2023-09-27 18:11:04

嗨,我有一个ObservableCollection每分钟获取数据。当它达到一个小时时,我想要清除第一个项目并移动所有项目,然后添加新项目,从而保持它的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;
    }
}

在一个可观察集合中维护60个元素

只要数一下列表中的项目,如果数量等于60,就删除最上面的项目。然后像平常一样插入新项。

if (Power.Count == 60)
    Power.RemoveAt(0);
Power.Add(new KeyValuePair<double, double>(i, SolarCellPower ));

如果你绑定你的ItemsSource而不是设置它,它会自动更新当集合的变化