如何绑定到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?
}
}
答案 0 :(得分:1)
试试这个。
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();
}
}
答案 1 :(得分:0)
更新列表后,您错过了对MyChart.DataBind()
(或MyChart.Series[0].Points.DataBind()
)的来电。您还可以从BindingSource
创建一个新的BindingList
,并绑定到该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
而不是列表,该列表应自动处理更新:
{{1}}