WPF图表Live Chart(四)动态折线图

时间:2024-03-22 20:25:16

前面介绍了Live Chart的基础和设置,接下将介绍如何绘制动态的折线图,实时更新数据的折线图。

效果预览

WPF图表Live Chart(四)动态折线图

前台代码

  <Grid x:Name="mygrid">
        <lvc:CartesianChart Series="{Binding SeriesCollection}" LegendLocation="Left">
            <lvc:CartesianChart.AxisX>
                <lvc:Axis Title="Time" Labels="{Binding Labels}" FontSize="14"></lvc:Axis>
            </lvc:CartesianChart.AxisX>
            <lvc:CartesianChart.AxisY>
                <lvc:Axis MaxValue="10" MinValue="-10" MinRange="-10" MaxRange="10"/>
            </lvc:CartesianChart.AxisY>
        </lvc:CartesianChart>
    </Grid>

后台代码

  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,5,2,1 };
        public MainWindow()
        {		
            InitializeComponent();
			//实例化一条折线图
            LineSeries mylineseries = new LineSeries();
            //设置折线的标题
            mylineseries.Title = "Temp";
            //折线图直线形式
            mylineseries.LineSmoothness = 0;
            //折线图的无点样式
            mylineseries.PointGeometry = null;
            //添加横坐标
            Labels =new List<string>{ "1", "3", "2", "4", "-3", "5", "2", "1" };
            //添加折线图的数据
            mylineseries.Values = new ChartValues<double>(temp);
            SeriesCollection = new SeriesCollection { };
            SeriesCollection.Add(mylineseries);
            _trend = 8;
			linestart();
			DataContext = this;
        }
        //连续折线图的方法
        public void linestart()
        {
            Task.Run(() =>
            {
                var r = new Random();
                while (true)
                {
                    Thread.Sleep(1000);
                    _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);
                    });
                }
            });
        }
    }