Search code examples
wpfcanvaswpf-controls

WPF - is there a way to remove specific child from Canvas.Children?


I am working on a charting control where I am plotting the "analysis range," which is just two vertical lines on the chart. A problem arises when I want to change the analysis range, because I don't know how to remove only the two analysis range lines, so I end up clearing the chart and plotting the actual data values and whatnot again. Is there a way to tag these UI elements (i.e. analysis range is a gridline UI element) so that I can remove them specifically? I suppose I could save the "index" of the UI element somewhere and delete these, but I am wondering if there is a cleaner way of doing this. Thanks a lot.


Solution

  • All UIElements have a UID which is a string. You could set the UID of the range lines to something predictable. Keep in Mind that UID must be unique. Then when you need to remove only the gridlines, you iterate through the Children collection gathering a list of the UI elements that need to be removed, then remove them.

    Something like this:

    Canvas c = new Canvas();
    c.Children.Add( new UIElement() { Uid = "Line1" } );
    c.Children.Add( new UIElement() { Uid = "Line2" } );
    c.Children.Add( new UIElement() { Uid = "Line3" } );
    c.Children.Add( new UIElement() { Uid = "Text1" } ); //This is added as a sample
    
    List<UIElement> itemstoremove = new List<UIElement>();
    foreach (UIElement ui in c.Children)
    {
      if (ui.Uid.StartsWith("Line"))
      {
        itemstoremove.Add(ui);
      }
    }
    foreach (UIElement ui in itemstoremove)
    {
      c.Children.Remove(ui);
    }
    

    That should work. A quick test of this code in debug shows the Children count at 1, with only the UIElement with Uid of Text1 present in the list.