0

Hi i am using oxyplot in my wpf application. When I try to add a lineseries object to plotmodel - I get an error

System.InvalidOperationException: "The element cannot be added, it already belongs to a PlotModel."

Here is my code

    public PlotController MyPlotController { get; set; }
    public PlotModel MyPlotModel { get; set; }
    public PlotVM()
    {
        MyPlotController = new PlotController();
        MyPlotModel = new PlotModel();
    }
    public void Plot(List<LineSeries> lineSeriesData)
    {
        MyPlotModel.Series.Clear();
        foreach (Series serie in lineSeriesData)
        {
            try
            {
                MyPlotModel.Series.Add(serie); //Get error here
            }
            catch (InvalidOperationException ex)
            {
                MyPlotModel = new PlotModel();
                MyPlotModel.Series.Add(serie); //Get error here
            }
        }
        MyPlotModel.InvalidatePlot(true);
    }

I don't understand how such an error can occur if the PlotModel.Series.Count property = 0 in the newly created PlotModel. Any help would be greatly appreciated.

Alexey
  • 1
  • 1
  • Could you please share where the `Plot` method is called from, especially how `lineSeriesData` parameter is created ? – Anu Viswan Dec 19 '21 at 23:58
  • Right, the input `lineSeriesData` could already be in another `PlotModel`'s collection. If `MyPlotModel` is the only plot in your application, another explanation might be that the same series occurs multiple times in this list. – Döharrrck Dec 20 '21 at 14:40
  • 1
    You can easily check whether it's about duplicates in the list by changing the second line in your method to `foreach (Series serie in lineSeriesData.Distinct())` to remove those duplicates. – Döharrrck Dec 20 '21 at 14:43

0 Answers0