简体   繁体   English

将对象列表绑定到图表

[英]Bind a List of Objects to Chart

I have a list of objects:我有一个对象列表:

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

the MyClass contains Properties Dtm and LastPrice that are updated real-time MyClass 包含实时更新的属性 Dtm 和 LastPrice

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谢谢

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 of a Series S1:List<T>绑定到Chart的最简单方法是将 List 设置为DataSource并设置 Series S1 的 X 值和 Y 值成员:

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

As for updating the chart you use the DataBind method:至于更新图表,您使用 DataBind 方法:

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:为此,您可以将DataBind调用权添加到相关属性的设置器中:

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.引用可以是static ,因为所有 List 元素都将更新同一个图表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM