1

こんにちは、毎分データを取得する ObservableCollection があります。1 時間に達したら、最初のアイテムをクリアしてすべてのアイテムを上に移動し、新しいアイテムを追加して 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 を設定する代わりに Bind すると、コレクションが変更されると自動的に更新されます。

于 2011-10-13T13:29:52.673 に答える