(一)WPF使用 Polyline 元素動態繪製折線
前端程式碼如下:
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_元素來繪製折線
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
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.FromSeconds(1);//1秒鐘產生一次中斷
dispatcherTimer.Tick += timer_Tick;//中斷入口函式
dispatcherTimer.IsEnabled = true;//開啟中斷
}
private void timer_Tick(object sender, EventArgs e)
{
currentSecond++;
double x = currentSecond * 10;//x值遞增*10
double y = rd.Next(1,200);//隨機產生y值
var point = new Point(x, y);
_myPolyline.Points.Add(point);//新增新的資料點
}
}
}
XAML程式碼如下:
<Window x:Class="使用_Polyline_元素來繪製折線.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:使用_Polyline_元素來繪製折線"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Canvas Height="400" Width="400">
<Polyline Name="_myPolyline"
Stroke="Black"
StrokeThickness="4" />
<Button Content="開始" Canvas.Left="-190" Canvas.Top="47" Width="75" Click="Button_Click" HorizontalAlignment="Left"/>
</Canvas>
</Window>
如果想要折線圖移動起來,稍微修改一下程式碼即可: