tags:

views:

452

answers:

1

How can you remove a wpf element by some kind of name? So sth like :

// Bar is some kind of usercontrol
Bar b = new Bar();
b.Tag = "someId";
theCanvas.Children.Add(b);

// Later to be removed without having the reference 
theCanvas.Children.RemoveElementWithTag("someId")

Except ofcourse, RemoveElementWithTag isn't an existing method...

+1  A: 

Could just use some LINQ:

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

That said, I highly suspect there's a cleaner, better performing way to achieve whatever it is you're trying to achieve.

HTH, Kent

Kent Boogaart
+1, since you could. I did it like that first, now I am using a dictionary for that. But is there really no way to get an element by id or sth?
Peter
Since the Children collection does only support getting things by id or reference there is no other way than to use LINQ/foreach to find the right element.
chrischu