我有一个椭圆(prew),我想通过标签(“p”)从canvas(canvas1)中删除.
我试过这个,但它不起作用:
var child = (from c in canvas1.Children
where "p".Equals(c.Tag)
select c).First();
canvas1.Children.Remove(child);
它给了我这个错误:
“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’.”
如何通过标记删除画布子项?
解决方法:
UIElementCollection实现了普通的旧IEnumerable,因此默认情况下与LINQ不兼容.您需要将其转换为强类型IEnumerable< T>在查询之前
var child = (from c in canvas1.Children.Cast<FrameworkElement>()
where "p".Equals(c.Tag)
select c).First();
canvas1.Children.Remove(child);
请注意,如果集合中存在非FrameworkElement(UIElement的另一个派生),则此代码可能会导致运行时错误.为了防止这种情况,你可能最好转到OfType方法
var child = (from c in canvas1.Children.OfType<FrameworkElement>()
where "p".Equals(c.Tag)
select c).First();
canvas1.Children.Remove(child);