无法在 WPF 中的画布上绘制某些点

本文关键字:绘制 WPF | 更新日期: 2023-09-27 18:31:28

我正在尝试在WPF中开发实时绘图图表。为此,我使用了 Canvas,并以 500 毫秒的间隔向折线系列添加一个点。在这里,我在可见屏幕中完成绘图后清除了以前的点。因此,当它发生时,"canClear"将是真的。

请参考下面的代码,在 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 中是否有更好的方法,请告诉我。(这只是此图表工具的概念证明)。

无法在 WPF 中的画布上绘制某些点

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