1

嗨,我有一个 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;
    }
}
4

1 回答 1

1

只需计算列表中的项目,如果计数等于 60,则删除最上面的项目。然后像往常一样插入新项目。

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

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

此外,如果您绑定 ItemsSource 而不是设置它,它将在集合更改时自动更新。

于 2011-10-13T13:29:52.673 回答