简体   繁体   English

按标签删除Canvas Child

[英]Remove a Canvas Child by tag

I have an ellipse (prew) that I want to delete from canvas (canvas1) by tag ("p"). 我有一个椭圆(prew),我想通过标签(“p”)从canvas(canvas1)中删除。 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'." “无法找到源类型'System.Windows.Controls.UIElementCollection'的查询模式的实现。''未找到的地方。考虑明确指定范围变量'c'的类型。”

How can I remove a canvas child by tag? 如何通过标记删除canvas子项?

The UIElementCollection implements plain old IEnumerable and hence isn't compatible with LINQ by default. UIElementCollection实现了普通的旧IEnumerable ,因此默认情况下与LINQ不兼容。 You need to convert it to a strongly typed IEnumerable<T> before querying 在查询之前,您需要将其转换为强类型的IEnumerable<T>

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 ). 请注意,如果集合中存在非FrameworkElementUIElement另一个派生),则此代码可能会导致运行时错误。 To protect against this you are probably better off going to the OfType method 为了防止这种情况,你可能最好转到OfType方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM