WPF使用Live Chart之动态更新数据
效果如下:
前台代码:
<Window x:Class="Chapter3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Chapter3"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
mc:Ignorable="d"
Title="Matrix OPeration" Height="400" Width="500">
<Grid>
<!--<Button Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Content="显示" Click="Button_Click"/>-->
<lvc:CartesianChart Name="sl" Grid.Row="1" Series="{Binding SeriesCollection}">
<lvc:CartesianChart.AxisX>
<lvc:Axis Title="Month" x:Name="slx" LabelFormatter="{Binding XFormatter}"/>
</lvc:CartesianChart.AxisX>
<lvc:CartesianChart.AxisY>
<lvc:Axis Title="Sales" x:Name="slY" LabelFormatter="{Binding YFormatter}"/>
</lvc:CartesianChart.AxisY>
</lvc:CartesianChart>
</Grid>
</Window>
font size=4 color=blue>后台代码:
#region NameSpaces
using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Collections.Generic;
using LiveCharts;
using LiveCharts.Wpf;
using System.Windows.Threading;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Chapter3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public SeriesCollection seriesCollection { get; set; }
public List<string> Labels { get; set; }
private double _trend;
private double[] temp = { 1, 3, 2, 4,3,6,3,2,2,4,7,4,2, -3, 5, 2, 1,7 };
public MainWindow()
{
InitializeComponent();
//实例化一条折线图
LineSeries line1 = new LineSeries();
//设置折线的标题
line1.Title = "Temp";
//设置折线的形式
line1.LineSmoothness = 1;
//折线图的无点样式
line1.PointGeometry = null;
//添加横坐标
Labels = new List<string>();
foreach (var item in temp)
{
Labels.Add(item.ToString());
}
//添加绘图的数据
line1.Values = new ChartValues<double>(temp);
seriesCollection = new SeriesCollection();
seriesCollection.Add(line1);
_trend = 8;
lineStart();
DataContext = this;
this.sl.Series = seriesCollection;
slx.Labels = Labels;
}
public void lineStart()
{
Task.Run(() =>
{
Random r = new Random();
while (true)
{
Thread.Sleep(100);
_trend = r.Next(-10, 10);
//通过Dispatcher在工作线程中更新窗体的UI元素
Application.Current.Dispatcher.Invoke(() =>
{
//更新横坐标时间
Labels.Add(DateTime.Now.ToString());
Labels.RemoveAt(0);
//更新纵坐标数据
seriesCollection[0].Values.Add(_trend);
seriesCollection[0].Values.RemoveAt(0);
});
}
});
}
}
}