如何连续绑定到图表

本文关键字:绑定 连续 何连续 | 更新日期: 2023-09-27 18:17:48

如何绑定到System.Windows.Forms.DataVisualization.Charting.Chart对象,以便在底层数据更改时更新图表?

我成功地绑定了一个带有底层双精度数组的图表:

double[] DoubleArray = new double[] {1.0, 2.0, 3.0, 4.0};
MyChart.Series[0].Points.DataBindY(DoubleArray);

但是当数组中的值被改变时,它不会更新图表。

所以我尝试用BindingList来实现绑定:

class Model
{
    public BindingList<double> DoubleList { get; set; }
    public Model()
    {
        //Initialize BindingList
        DoubleList = new BindingList<double>();
        DoubleList.Add(1.0);
        DoubleList.Add(2.0);
        DoubleList.Add(3.0);
        DoubleList.Add(4.0);
    }
    public void UpdateModel(double y0, double y1, double y2, double y3)
    {
        //Just a simple example - of course you could do checks and only
        //update values where required.
        DoubleList[0] = y0;
        DoubleList[1] = y1;
        DoubleList[2] = y2;
        DoubleList[3] = y3;
    }
}

代码放置形式:

class MyForm : Form
{
    Model _Model = new Model();
    public MyForm()
    {
        InitializeComponent();
        MyChart.Series[0].Points.DataBindY(_Model.DoubleList); //Binds successfully and displays chart with initial values.
    }
    //Why doesn't this update the chart?
    private void button1_Click(object sender, EventArgs e)
    {
        _Model.UpdateModel(4.0, 5.0, 6.0, 7.0);  //Has no effect on chart... what do I do wrong?
    }
}

如何连续绑定到图表

试试这个

public partial class MyForm : Form
{
    Model _Model = new Model();
    public MyForm()
    {
        InitializeComponent();
        MyChart.Series.First().XValueMember = "X";
        MyChart.Series.First().YValueMembers = "Y";
        MyChart.DataSource = _Model.DoubleList;
    }
    private void button1_Click( object sender, EventArgs e )
    {
        _Model.UpdateModel( 4.0, 5.0, 6.0, 7.0 );
        MyChart.DataBind();
    }
}

您在更新列表后错过了呼叫MyChart.DataBind()(或MyChart.Series[0].Points.DataBind())。您也可以从您的BindingList创建一个新的BindingSource,并绑定到它而不是列表,它应该自动处理更新:

BindingSource source = new BindingSource(_Model.DoubleList, null);
MyChart.Series[0].Points.DataBindY(source);
// In your button click method
_Model.Update(4, 5, 6, 7); // This should update your chart, since you used a BindingSource