标签:
最近需要在Wpf程序中显示曲线,感觉Sparrow.Chart.Wpf控件不错(http://sparrowtoolkit.codeplex.com/),完全开源的一个控件支持,可以通过nuget下载。源代码中的例子完全采用MVVM方式实现,我项目中需求是完全通过代码创建控件,通过代码绑定数据,因此经过简单,实现了一个基本的例子:
首先顶一个CPU类(来自sparrow源代码):
public class CPU { private DateTime time; public DateTime Time { get { return time; } set { time = value; } } private double percentage; public double Percentage { get { return percentage; } set { percentage = value; } } private double memoryUsage; public double MemoryUsage { get { return memoryUsage; } set { memoryUsage = value; } } public CPU() { } public CPU(DateTime time, double percentage, double memoryUsage) { this.Time = time; this.Percentage = percentage; this.MemoryUsage = memoryUsage; }
然后通过一个函数产生随机数据:
private void CreateSomeData() { DateTime dt = DateTime.Now; System.Random rad=new Random(System.DateTime.Now.Millisecond); for(int n=0;n<100;n++) { dt=dt.AddSeconds(1); CPU cpu= new CPU(dt,rad.Next(100),51); m_listCpu.Add(cpu); } }
最后通过代码动态创建chart控件:
CreateSomeData(); //窗体加载事件 SparrowChart chart = new SparrowChart(); DateTimeXAxis xaxis = new DateTimeXAxis(); xaxis.Interval = "0:0:1"; chart.XAxis = xaxis; xaxis.Visibility = Visibility.Collapsed; LinearYAxis yaxis = new LinearYAxis(); chart.YAxis = yaxis; yaxis.MinValue = 0; yaxis.MaxValue = 100; LineSeries ser = new LineSeries(); chart.Series.Add(ser); ser.XPath = "Time"; ser.YPath = "Percentage"; ser.PointsSource = m_listCpu; rootLayout.Children.Add(chart);
程序运行效果图如下:
标签:
原文地址:http://www.cnblogs.com/sfcyyc/p/4642894.html