1.问题或需求描述:
使用 C# 实现动态图表,动态数据呈现
2.测试环境:
win10, vs2019, dotnet 4.5
3.解决方法或原理:
1>创建用户控件窗体
2>添加一个 System.Windows.Forms.DataVisualization.Charting.Chart 以呈现图表
2>添加一个 System.Windows.Forms.Timer 以构造随时间变化的随机数据(动态演示,数据刷新频率取决于此timer控件通知频率)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace DynamicChart
{
public partial class DChart : UserControl
{
static readonly int xPointNum = 25;
Queue<int> dataQueue = new Queue<int>();
List<int> chartXList = new List<int>();
public DChart()
{
InitializeComponent();
this.Location = new Point(0, 0);
dataQueue.Clear();
for (int i = 0; i < xPointNum; i++)
{
dataQueue.Enqueue(0);
chartXList.Add(i+1);
}
chart1.Legends[0].Enabled = false;
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
}
private void DChart_Resize(object sender, EventArgs e)
{
chart1.Size = this.Size;
}
private void timerClock_Tick(object sender, EventArgs e)
{
if (DesignMode) return;
int number = new Random().Next(0,50);
if (dataQueue.Count >= xPointNum) dataQueue.Dequeue();
dataQueue.Enqueue(number);
chart1.Series[0].Points.DataBindXY(chartXList, dataQueue);
}
private void DChart_Load(object sender, EventArgs e)
{
if (DesignMode)
{
timerClock.Enabled = false;
Random random = new Random();
for (int i = 0; i < xPointNum; i++)
{
if (dataQueue.Count >= xPointNum) dataQueue.Dequeue();
dataQueue.Enqueue(random.Next(0, 100));
}
chart1.Series[0].Points.DataBindXY(chartXList, dataQueue);
}
}
}
}
4.结果演示
5.备注
本文旨在演示动态图表的一种实现原理,不在于解决任何确切问题。
如读者测试实践中有困难,可向作者反馈,作者愿意提供适当援助。