2016-01-22 30 views
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中做到这一点。 (这只是这个图表工具的概念证明)。

+0

你的问题是什么?它不工作吗? – Clemens

+0

我无法使用上面的代码在Canvas上绘制折线。 –

+0

“我无法”是什么意思?您是否看到黑色Canvas背景,但是没有出现白色折线,尽管您已在'_vm_DataAddedEvent'中设置了一个断点以确保它真的被调用? – Clemens

回答

0

克莱门斯,建议帮助我解决了这个问题。因此,我已经向前推进了我的POC开发。谢谢。