WPF基于Live Charts实现波形图

using LiveCharts;//livecharts.net
using LiveCharts.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public SeriesCollection seriesColloection { get; set; }//系列集合
        AxesCollection axisx = new AxesCollection();
        private double receivedData;
        Task t;
        public List<string> labels { get; set; }
        public double[] yA = { 67,72,81,85,90,80,25};
        public MainWindow()
        {
            InitializeComponent();
            LineSeries lineA = new LineSeries();//一条折线
            lineA.Title = "A";
            lineA.LineSmoothness = 0;
            lineA.PointGeometry = null;
            labels = new List<string> { "2019/10/10", "2019/10/12", "2019/10/14", "2019/10/16", "2019/10/18", "2019/10/20" };//横坐标数据
            lineA.Values = new ChartValues<double>(yA);
            seriesColloection = new SeriesCollection();
            seriesColloection.Add(lineA);
            this.lvcChart.lvcsub.Series = seriesColloection;
            this.lvcChart.lvcsub.AxisX.Add(new Axis {Title="A",Labels= labels });
            this.lvcChart.label1.Content = "Original"; 
        }
        public void onData_Received() {

            t=Task.Run(()=>//从ThreadPool选一个可用的thread;没有则新建一个
            {
                var fromRandom = new Random();
                while (true)
                {
                    Thread.Sleep(1000);//每隔半秒
                    receivedData = fromRandom.Next(-100,100);
                    this.Dispatcher.Invoke(()=> {//通过Dispatcher更新控件数据。UI线程之一Dispatcher负责控件相关的事件的处理
                        labels.Add(DateTime.Now.AddMilliseconds(100).ToString()); //更新X轴数据
                        labels.RemoveAt(0);
                        seriesColloection[0].Values.Add(receivedData);//更新Y轴数据
                        seriesColloection[0].Values.RemoveAt(0);
                        this.lvcChart.label1.Content = "Live";
                    });

                }


            });
        }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            onData_Received();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (t != null)
            {
                t.Dispose();//异常
                t = null;
                GC.Collect();
            }
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/80028366local/p/12769504.html