上一个程序的运行结果,会不断随机产生数据并且自动绘制直线,但是折线图不会移动,稍微修改一下上一个程序即可轻松实现折线图移动。前段代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Windows.Threading;
namespace 使用_Polyline_元素来绘制折线
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
private int currentSecond = 0;
Random rd = new Random();
private DispatcherTimer dispatcherTimer = new DispatcherTimer();
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(1000);//1秒钟产生一次中断
dispatcherTimer.Tick += timer_Tick;//中断入口函数
dispatcherTimer.IsEnabled = true;//开启中断
}
private void timer_Tick(object sender, EventArgs e)
{
currentSecond++;
double x = currentSecond * 10;
double y = rd.Next(1,200);
var point = new Point(x, y);
_myPolyline.Points.Add(point);//添加新的数据点
if (currentSecond > 10 )
{
_myPolyline.Points.RemoveAt(0);//移除数据点索引0的位置
_myCanvas.Margin = new Thickness(-20 * currentSecond+500, 0, 0, 0);
}
}
}
}
如果不移除数据点索引0的位置,程序依然会运行,但是随着运行时间的增加,内存会不断增加,CPU使用率也会不断增加
XAML代码如下:
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:使用_Polyline_元素来绘制折线"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">