将对象列表绑定到图表 [英] Bind a List of Objects to Chart

查看:66
本文介绍了将对象列表绑定到图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表:

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

MyClass包含实时更新的属性Dtm和LastPrice

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?

谢谢

推荐答案

有关将数据绑定到系列(图表控件),请参见此处!

List<T>绑定到Chart的最简单方法是将列表设置为DataSource并设置X和Y值成员:

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";

对于更新图表,您可以使用DataBind方法:

As for updating the chart you use the DataBind method:

chart1.DataBind();

现在您有两个选择:

您知道何时更改;那么您只需在更改后添加呼叫即可.

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.

为此,您可以将DataBind调用直接添加到相关属性的设置器中:

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) );

引用可以是static,因为所有List元素都将更新同一图表.

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

这篇关于将对象列表绑定到图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆