Ionică Bizău
Ionică Bizău

Reputation: 113355

Remove a Canvas Child by tag

I have an ellipse (prew) that I want to delete from canvas (canvas1) by tag ("p"). I tried this, but it doesn't work:

var child = (from c in canvas1.Children
             where "p".Equals(c.Tag)
             select c).First();
canvas1.Children.Remove(child);

It gave me this error:

"Could not find an implementation of the query pattern for source type 'System.Windows.Controls.UIElementCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'c'."

How can I remove a canvas child by tag?

Upvotes: 3

Views: 2696

Answers (2)

JaredPar
JaredPar

Reputation: 754665

The UIElementCollection implements plain old IEnumerable and hence isn't compatible with LINQ by default. You need to convert it to a strongly typed IEnumerable<T> before querying

var child = (from c in canvas1.Children.Cast<FrameworkElement>()
             where "p".Equals(c.Tag)
             select c).First();
canvas1.Children.Remove(child);

Note that this code is suspectible to a runtime error if there is a non FrameworkElement in the collection (another derivation of UIElement). To protect against this you are probably better off going to the OfType method

var child = (from c in canvas1.Children.OfType<FrameworkElement>()
             where "p".Equals(c.Tag)
             select c).First();
canvas1.Children.Remove(child);

Upvotes: 10

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

var child = (from FrameworkElement c in canvas1.Children
             where "p".Equals(c.Tag)
             select c).First();
canvas1.Children.Remove(child);

or

var child = (from c in canvas1.Children.Cast<FrameworkElement>()
             where "p".Equals(c.Tag)
             select c).First();
canvas1.Children.Remove(child);

Upvotes: 2

Related Questions