Search code examples
c#wpflinqoxyplot

How to remove or hide comments on an OxyPlot graph?


How to remove or hide comments on an OxyPlot graph? I am doing this but it does not work:

public void AddAnnotation(IEnumerable<Annotation> annotations)
{
  foreach (var annotation in annotations)
  {
    MyOxyPlotModel.Annotations.Add(annotation);
  }

  RefreshAxisSeriesPlot();
}

public void RemoveAnnotation(IEnumerable<Annotation> annotations)
{
  foreach (var annotation in annotations)
  {
    MyOxyPlotModel.Annotations.Remove(annotation);
  }

  RefreshAxisSeriesPlot();
}

private void RefreshAxisSeriesPlot() => MyOxyPlotModel.InvalidatePlot(true);

With this code, adding annotations works, but removing annotations does not work.

Edit:

OK, I found the problem in my code. In fact, I had not completed the evaluation of my LINQ query from which I get my IEnumerable<Annotation> annotations… And it recreates a new Annotation object at each iteration of IEnumerable<Annotation> annotations.


Solution

  • You are probably passing in different instances of Annotation to your RemoveAnnotation method compared to the instances that you have previously added to MyOxyPlotModel.Annotations. Passing an instance that doesn't exist in Annotations to Annotations.Remove won't remove anything since the annotation to be removed cannot be determined.

    Make sure that you use the same instances in your AddAnnotation and RemoveAnnotation methods, or use a property of the annotation to compare it with the existing one.

    If you for example use annotations that derive from TextualAnnotation, you could compare them by the Text property. Something like this:

    public void RemoveAnnotation(IEnumerable<Annotation> annotations)
    {
        foreach (var annotation in annotations)
        {
            if (MyOxyPlotModel.Annotations.Contains(annotation))
                MyOxyPlotModel.Annotations.Remove(annotation);
            else if (annotation is TextualAnnotation ta)
            {
                var existingTa = MyOxyPlotModel.Annotations.OfType<TextualAnnotation>().FirstOrDefault(x => x.Text == ta.Text);
                if (existingTa != null)
                    MyOxyPlotModel.Annotations.Remove(existingTa);
            }
        }
    
        RefreshAxisSeriesPlot();
    }