0
我試圖在WPF中開發一個實時繪圖圖表。爲此,我使用了Canvas,並在500毫秒的時間間隔內爲Polyline系列添加了一個點。在完成可見屏幕繪圖之後,我將清除以前的點。所以當它發生時,'canClear'將是真實的。無法在WPF中的畫布上繪製一些點
請參考下面的代碼, 在Xaml.Cs:
public partial class Chart : UserControl
{
private ChartViewModel _vm;
public Chart()
{
InitializeComponent();
_vm = new ChartViewModel();
_vm.DataAddedEvent += _vm_DataAddedEvent;
this.Loaded += (s, e) =>
{
this.DataContext = _vm;
};
}
void _vm_DataAddedEvent(Point pt, bool canClear)
{
this.Dispatcher.Invoke(() =>
{
if (canClear)
{
this.pointLine.Points.RemoveAt(0);
}
this.pointLine.Points.Add(pt);
this.canVas.UpdateLayout();
});
}
}
在XAML:
<UserControl x:Class="ChartControl.ChartTool.Chart"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Background="Blue" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch">
<Canvas x:Name="canVas" Background="Black" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Polyline x:Name="pointLine" Stroke="White" StrokeThickness="1"/>
</Canvas>
視圖模型:
public delegate void DataAdded(Point pt, Boolean canClear);
public class ChartViewModel : BaseViewModel
{
public event DataAdded DataAddedEvent;
public ChartViewModel()
{
_points = new List<Point>();
_pointSeries = new PointCollection();
// _rand = new Random(0);
_timer = new Timer(OnTimerTick, null, 0, 500);
}
private double _x = 20.0;
private void OnTimerTick(object state)
{
_x += 0.01;
Point pt = new Point(_x, 50);
_points.Add(pt);
if (_counter < 100)
{
if (DataAddedEvent != null)
{
DataAddedEvent(pt, false);
}
_counter++;
}
else
{
if (DataAddedEvent != null)
{
DataAddedEvent(pt, true);
}
}
}
// private Random _rand;
private int _counter;
private PointCollection _pointSeries;
public PointCollection PointSeries
{
get { return _pointSeries; }
set { _pointSeries = value; }
}
private Timer _timer;
private List<Point> _points;
}
請建議我如果我在這裏做錯了什麼,或者有沒有更好的方式在WPF中做到這一點。 (這只是這個圖表工具的概念證明)。
你的問題是什麼?它不工作嗎? – Clemens
我無法使用上面的代碼在Canvas上繪製折線。 –
「我無法」是什麼意思?您是否看到黑色Canvas背景,但是沒有出現白色折線,儘管您已在'_vm_DataAddedEvent'中設置了一個斷點以確保它真的被調用? – Clemens