【问题标题】:How to make Polyline draw WPF c#?如何让 Polyline 绘制 WPF c#?
【发布时间】:2022-11-19 01:50:16
【问题描述】:

我是 wpf 的新手,我有一个任务需要绘制一个实时图形,其中包含一组每秒或更少变化一次的数字。我搜索了很多解决方案,最适合我的选择是使用标准图形,即“折线”元素作为使用“PointCollection”的绑定,我可以用单独的方法计算它。下面的代码不起作用,我不明白如何让它工作。最终目标是制作与 Windows 10 任务管理器中相同的图形

这是带有属性链接的折线代码

<Polyline Name="Graph"
          StrokeLineJoin="Round"       
          Stroke="Red"
          Points="{Binding Points}">
</Polyline>

在这里,我试图实现一个 MVVM 模式并测试我分配随机坐标值的代码,然后我将进行正常计算,但这个解决方案不起作用,我不明白我需要做什么才能拥有我的图表实时绘制在一个新线程中,就像在任务管理器中一样

class MainViewModel : ViewModelBase
    {
        PointCollection _Points;
        public PointCollection Points
        {
            get { return _Points; }
            set
            {
                _Points = value;
                RaisePropertyChanged(() => Points);
            }
        }

        void DrawGraph()
        {
            Points = new PointCollection();

            Task.Factory.StartNew(() =>
            {
                Random rnd = new Random();

                double y;

                for (double x = 0; x < 490; x = x + 2)
                {
                    y = rnd.Next(0, 235);

                    Points.Add(new Point(x, y));

                    Task.Delay(1000).Wait();
                }

            });
        }
    }

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    PointCollection 是一个依赖对象。而且您只能在一个线程中使用它。 ``CS private readonly Random rnd = new Random();

        private async void DrawGraph()
        {
            Points = new PointCollection();
    
            double y;
    
            for (double x = 0; x < 490; x = x + 2)
            {
               y = rnd.Next(0, 235);
    
               Points.Add(new Point(x, y));
    
               await Task.Delay(1000);
            }
    
         }
    

    【讨论】:

    • 这行不通。当您将元素添加到其 Points 集合时,Polyline 不会更新。
    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 2019-03-11
    相关资源
    最近更新 更多