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();
            }
        }

    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM