【目錄】DynamicDataDisplay - 簡(jiǎn)書
一、概述
本文介紹使用DynamicDataDisplay繪制動(dòng)態(tài)折線圖锯仪。
一般的場(chǎng)景是數(shù)據(jù)綁定到VM中迅诬,然后在VM中動(dòng)態(tài)添加數(shù)據(jù)點(diǎn)濒蒋,圖表實(shí)時(shí)更新。
下面進(jìn)行實(shí)現(xiàn)鬼癣。
二回溺、演示
三悦荒、實(shí)現(xiàn)
第一步:新建項(xiàng)目
1.新建項(xiàng)目D3DynamicDemo
2.添加Nuget包:DynamicDataDisplayReloaded
第二步:新建MainWindowViewModel唯欣,并編寫以下代碼
public class MainWindowViewModel : INotifyPropertyChanged
{
private List<Point> _points { get; set; } = new List<Point>();
public EnumerableDataSource<Point> PointDataSource
{
get
{
// 每次都需要重新創(chuàng)建數(shù)據(jù)源
var points = new List<Point>();
for (int i = 0; i < _points.Count; i++)
points.Add(_points[i]);
var ds = new EnumerableDataSource<Point>(points);
ds.SetXYMapping(pt => pt);
return ds;
}
}
public MainWindowViewModel()
{
InitDynamicDataSource();
}
private void InitDynamicDataSource()
{
// 模擬動(dòng)態(tài)添加數(shù)據(jù)
Task.Factory.StartNew(async () =>
{
var random = new Random();
var index = 0;
while (true)
{
// 添加一個(gè)模擬數(shù)據(jù)點(diǎn)
_points.Add(new Point(index++, random.Next(300, 500)));
// 通知數(shù)據(jù)源有更改
OnPropertyChanged(nameof(PointDataSource));
await Task.Delay(500);
}
});
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
首先實(shí)現(xiàn)了INotifyPropertyChanged接口,這樣便有了屬性更改通知界面刷新的能力搬味。
然后定義了PointDataSource數(shù)據(jù)源境氢,在其get方法中重新創(chuàng)建數(shù)據(jù)源并返回。
最后模擬動(dòng)態(tài)添加數(shù)據(jù)碰纬,通過屬性通知更改的方式萍聊,實(shí)現(xiàn)刷新界面。
第三步:在MainWindow.xaml中編寫以下代碼
<Window x:Class="D3DynamicDemo.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:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
xmlns:local="clr-namespace:D3DynamicDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="動(dòng)態(tài)折線圖"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid Margin="8">
<d3:ChartPlotter>
<d3:LineGraph x:Name="lineGraph" DataSource="{Binding PointDataSource}" />
</d3:ChartPlotter>
</Grid>
</Window>
這里主要是將LineGraph的DataSource綁定到了VM中的PointDataSource屬性上悦析。
第四步:恭喜寿桨,已完成
四、環(huán)境
開發(fā)工具:Visual Studio
開發(fā)語(yǔ)言:C#
目標(biāo)框架:.Net 6.0
Nuget包:DynamicDataDisplayReloaded