1

I have canvas with few labels, lines and rectangles. I want to get only Labels from canvas, and then to replace with another labels. Is it possible to get only labels? I try to foreach elements but is give me exception:

Unable to cast object of type 'System.Windows.Shapes.Line' to type 'System.Windows.Controls.Label'.

I try with this code:

foreach (System.Windows.Controls.Label child in canvas.Children)
{
    try
    {
        double.Parse(child.Content.ToString());
    }
    catch (FormatException)
    {
        continue;
    }

    canvas.Children.Remove(child);
}

Anybody know how can get only labels from canvas.

Thanks in advance

evelikov92
  • 755
  • 3
  • 8
  • 30

1 Answers1

5

You should use Enumerable.OfType :

foreach (var child in canvas.Children.OfType<System.Windows.Controls.Label>())
{
}

From msdn:

The OfType(IEnumerable) method returns only those elements in source that can be cast to type TResult.

w.b
  • 11,026
  • 5
  • 30
  • 49
  • thanks...did`nt knew that. – Abhinav Sharma Feb 09 '16 at 06:05
  • Note, that this won't find *all* child `Label`s. The result will contain only direct children. – Dennis Feb 09 '16 at 06:12
  • @Dennis - yes, but the OP's said `I have canvas with few labels, lines and rectangles`, also it's unusual to nest other panels in a `Canvas` – w.b Feb 09 '16 at 06:15
  • @w.b: what do you mean - unusual? Canvas is just a `Panel`. It could contain anything. While this is (possible) unusual to you, this can be usual to anybody else (e.g., to me :) ). Anyway, this was just a warning for OP. Logically your code is OK and will filter collection. – Dennis Feb 09 '16 at 06:17
  • @Dennis - the OP said `I have canvas with few labels, lines and rectangles`, didn't mention other Panels – w.b Feb 09 '16 at 06:18