如何在WPF中动态更新PolyLine



我的目标是有一条多段线,我可以在其中每2秒添加一个点,并且多段线在UI中反映它。

我有一个PolyLine,它使用值转换器绑定到ObservableCollection,如下所示:

XAML

<Polyline Points="{Binding OutCollection,Mode=TwoWay,Converter={StaticResource pointConverter}}" Stroke="Blue" StrokeThickness="15" Name="Line2"  />

值转换器

 public class PointCollectionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        PointCollection outCollection = new PointCollection();
        if (value is ObservableCollection<Point>)
        {
            var inCollection = value as ObservableCollection<Point>;
            foreach (var item in inCollection)
            {
                outCollection.Add(new Point(item.X, item.Y));
            }
            return outCollection;
        }
        else
            throw new Exception("Wrong Input");
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new Exception("Wrong Operation");
    }
}

在代码隐藏文件中:

public MainWindow()
    {
        InitializeComponent();
        this.DataContext = vm;
        InitTimer();
    }
    private void InitTimer()
    {
        dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(TickHandler);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
        dispatcherTimer.Start();
    }
    int counter = 0;
    private void TickHandler(object sender, EventArgs e)
    {
        double val = (counter * counter) * (0.001);
        var point = new Point(counter, val);
        vm.OutCollection.Add(point);
        vm.OutCollection.CollectionChanged += OutCollection_CollectionChanged;         
        counter++;
    }

ViewModel:

public class ViewModel : ViewModelBase
{
    public ObservableCollection<Point> OutCollection
    {
        get
        {
            return m_OutCollection;
        }
        set
        {
            m_OutCollection = value;
            this.OnPropertyChanged("OutCollection");
        }
    }

}

    private ObservableCollection<Point> m_OutCollection;

    public ViewModel()
    {
        OutCollection = new ObservableCollection<Point>();
    }

它不起作用。感谢任何帮助?!?

我自己解决了。

ObservableCollection可能没有帮助,但有帮助的是添加

Line2.GetBindingExpression(Polyline.PointsProperty).UpdateTarget();

TickHandler()

相关内容

  • 没有找到相关文章

最新更新