How do I correctly update my chart values? (In real time)

我只是一个虾纸丫 提交于 2019-12-01 18:07:31
bto.rdz

Live-Charts tries to keep it simple. The logic is to use a generic collection with the type you need to plot, and then as easy as adding/removing or updating any element in this collection then your chart will be updated.

To answer your question, you normally need to:

public partial class Form1 : Form
{
    private ObservableValue value1;

    public Form1()
    {
        InitializeComponent();

        //int val1 = int.Parse(Settings.Default.Value1);

        value1 = new ObservableValue(3);
        //...

        cartesianChart1.Series.Add(new LineSeries 
        {
            Values = new ChartValues<ObservableValue> { value1, ... },
        });
    }

    private void changeValue1ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        value1.Value = 10;
        Settings.Default.Value1 = "10";
        Settings.Default.Save();
        this.Text = Settings.Default.Value1;

    }
}

Then the library will handle animations and the update

Note: The question is about LiveCharts. But this answer is posted based on MSChart. To see the answer about LiveCharts see other answer.

Chart supports data-binding. Use data-binding and update data source then refresh chart. For example:

DataTable table = new DataTable();
Random random = new Random();
private void Form1_Load(object sender, EventArgs e)
{
    table.Columns.Add("X", typeof(int));
    table.Columns.Add("Y", typeof(int));
    for (int i = 0; i < 10; i++)
        table.Rows.Add(i+1, random.Next(100));
    chart1.Series[0].ChartType = 
        System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
    chart1.Series[0].XValueMember = "X";
    chart1.Series[0].YValueMembers = "Y";
    chart1.DataSource = table;
    chart1.ChartAreas[0].AxisX.Interval = 1;
    chart1.ChartAreas[0].AxisX.Minimum = 0;
    chart1.ChartAreas[0].AxisX.Maximum = 10;
    chart1.ChartAreas[0].AxisY.Interval = 10;
    chart1.ChartAreas[0].AxisY.Minimum = 0;
    chart1.ChartAreas[0].AxisY.Maximum = 100;
    chart1.DataBind();
    var timer = new Timer() { Interval= 300};
    timer.Tick += timer_Tick;
    timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
        table.Rows[i][1]= random.Next(100);
    chart1.DataBind();
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!