Live-Charts在WPF中的使用
一、简介
官方地址:Live-Charts (github.com)。Live Charts (lvcharts.net)。
这里说一下高性能的LiveCharts.Geared,这个支持大数据量,最多到百万级别,听说不是免费的,但是我在NuGet中安装了可以使用,不知道后面会不会过期。但是可以从其他途径弄到破解版的,只需要替换dll即可。推荐大家直接学习使用LiveCharts.Geared。
这是作者NuGet包的路径,我们将破解版的dll替换lib文件夹中的就可以。
二、简单使用
需要引入命名空间:
xmlns:geared="clr-namespace:LiveCharts.Geared;assembly=LiveCharts.Geared"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
创建控件:
<!--Here we disable tooltips and hovering to get a better performance-->
<lvc:CartesianChart
AnimationsSpeed="0:0:0.5"
DataTooltip="{x:Null}"
DisableAnimations="True"
Hoverable="False">
<lvc:CartesianChart.Series>
<geared:GLineSeries
Fill="Transparent"
LineSmoothness="1"
PointGeometry="{x:Null}"
Stroke="#F34336"
StrokeThickness="6"
Values="{Binding ChartValues}" />
</lvc:CartesianChart.Series>
<lvc:CartesianChart.AxisX>
<lvc:Axis
LabelFormatter="{Binding DateTimeFormatter}"
MaxValue="{Binding AxisMax}"
MinValue="{Binding AxisMin}"
Unit="{Binding AxisUnit}">
<lvc:Axis.Separator>
<lvc:Separator Step="{Binding AxisStep}" />
</lvc:Axis.Separator>
</lvc:Axis>
</lvc:CartesianChart.AxisX>
</lvc:CartesianChart>
在VM中定义了如下的属性:
private double _trend;
private double _axisMax;
private double _axisMin;
public double AxisMax
{
get { return _axisMax; }
set
{
_axisMax = value;RaisePropertyChanged();
}
}
public double AxisMin
{
get { return _axisMin; }
set
{
_axisMin = value;RaisePropertyChanged();
}
}
public GearedValues<MeasureModel> ChartValues { get; set; }
public Func<double, string> DateTimeFormatter { get; set; }
public double AxisStep { get; set; }
public double AxisUnit { get; set; }
业务逻辑如下:
var mapper = Mappers.Xy<MeasureModel>()
.X(model => model.DateTime.Ticks) //use DateTime.Ticks as X
.Y(model => model.Value); //use the value property as Y
//lets save the mapper globally.
Charting.For<MeasureModel>(mapper);
//the values property will store our values array
ChartValues = new GearedValues<MeasureModel>();
ChartValues.WithQuality(Quality.Low);
//lets set how to display the X Labels
DateTimeFormatter = value => new DateTime((long)value).ToString("mm:ss");
//AxisStep forces the distance between each separator in the X axis
AxisStep = TimeSpan.FromSeconds(1).Ticks;
//AxisUnit forces lets the axis know that we are plotting seconds
//this is not always necessary, but it can prevent wrong labeling
AxisUnit = TimeSpan.TicksPerSecond;
SetAxisLimits(DateTime.Now);
Task.Run(() =>
{
var r = new Random();
while (true)
{
Thread.Sleep(150);
var now = DateTime.Now;
_trend += r.Next(-8, 10);
ChartValues.Add(new MeasureModel
{
DateTime = now,
Value = _trend
});
SetAxisLimits(now);
//lets only use the last 150 values
if (ChartValues.Count > 150) ChartValues.RemoveAt(0);
}
});
private void SetAxisLimits(DateTime now)
{
AxisMax = now.Ticks + TimeSpan.FromSeconds(1).Ticks; // lets force the axis to be 1 second ahead
AxisMin = now.Ticks - TimeSpan.FromSeconds(8).Ticks; // and 8 seconds behind
}
我们往集合中添加数据,在view中就会自动更新,一个动态更新的线图就简单完成了。更多复杂的功能可以参考链接中的教程。