Bind a List of Objects to Chart

2019-05-28 10:38发布

问题:

I have a list of objects:

List<MyClass> MyList = new List<MyClass>();

the MyClass contains Properties Dtm and LastPrice that are updated real-time

public class MyClass
{
    int dtm;
    double lastPrice = 0;

    public int Dtm
    {
        get { return dtm; }
        set { dtm = value; }
    }

    public double LastPrice
    {
        get { return lastPrice; }
        set { lastPrice = value; }
    }

}

I want now a chart lined to the list that updates automatically each time the properties change. Any idea on how to do it?

Thanks

回答1:

For an overview of Binding Data to Series (Chart Controls) see here!

The easiest way to bind your List<T> to a Chart is simply to set the List as DataSource and to set the X- and Y-Value members:

chart1.DataSource = MyList;
S1.XValueMember = "Dtm";
S1.YValueMembers = "LastPrice";

As for updating the chart you use the DataBind method:

chart1.DataBind();

Now you have two options:

Either you know when the values change; then you can simply add the call after the changes.

But maybe you don't know just when those changes occur or there are many actors that all may change the list.

For this you can add the DataBind call right into the setter of the relevant property:

public class MyClass
{
    int dtm;
    double lastPrice = 0;
    public static Chart chart_ { get; set; }

    public int Dtm
    {
        get { return dtm; }
        set { dtm = value; }
    }

    public double LastPrice
    {
        get { return lastPrice; }
        set { lastPrice = value; chart_.DataBind(); }
    }

     // a constructor to make life a little easier:
    public MyClass(int dt, double lpr)
    { Dtm = dt; LastPrice = lpr; }
}

For this to work the List must learn about the chart to keep updated. I have added a reference to the class already. So before adding/binding points we set a chart reference:

MyClass.chart_ = chart1;  // set the static chart to update

// a few test data using a Random object R:
for (int i = 0; i < 15; i++)
    MyList.Add(new MyClass(R.Next(100) + 1 , R.Next(100) / 10f) );

The reference can be static, as all List elements will update the same chart.