How to Dynamically Update a PolyLine in WPF?

1.5k Views Asked by At

My Goal is to have a Polyline in which I can add a point every 2 seconds and the PolyLine reflects it in UI.

I have a PolyLine that is bound to an ObservableCollection using a Value Converter as follows:

XAML

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

Value Converter

 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");
    }
}

And in code behind file:

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>();

    }

Its not working. Any help is appreciated?!?

1

There are 1 best solutions below

0
On

I solved it myself.

The ObservableCollection might not help, but what helped is to add

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

in the TickHandler()