如何通过它删除画布上的wpf元素';谁的标签名?

如何通过它删除画布上的wpf元素';谁的标签名?,wpf,canvas,Wpf,Canvas,如何以某种名称删除wpf元素?例如: // 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") 当然,除了RemoveElementWithTag之外

如何以某种名称删除wpf元素?例如:

// 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")

当然,除了RemoveElementWithTag之外,RemoveElementWithTag不是一个现有的方法…

可以使用一些LINQ:

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

也就是说,我高度怀疑有一种更干净、表现更好的方式来实现你想要实现的目标

+1,因为你可以。我先是这样做的,现在我用字典来解释。但是真的没有办法通过id或其他方式获取元素吗?因为Children集合只支持通过id或引用获取内容,所以除了使用LINQ/foreach来查找正确的元素之外,没有其他方法。