Home > Software design >  How to remove a tagged WPF object from Canvas?
How to remove a tagged WPF object from Canvas?

Time:05-27

the code below gives me the following error:

CS1061 UIElementCollection does not contain a definition for Where and no accessible extension method Where accepting a first argument of type UIElementCollection could be found (are you missing a using directive or an assembly reference?)

var object = main.Children.Where(c => "platform1".Equals(c.Tag)).First();
main.Children.Remove(object);

How to get it to work?

Thanks!

CodePudding user response:

The Children property type UIElementCollection does not implement the generic interface IEnumerable<T>, so you can't use it as source of the Enumerable extension methods like Where.

You would have to add a type cast method like

var obj = main.Children.Cast<UIElement>().Where(...);

Since you also want to access the Tag property of the FrameworkElement subclass, use something like this instead:

var obj = main.Children
              .OfType<FrameworkElement>()
              .Where(c => "platform1".Equals(c.Tag))
              .First();

Or shorter:

var obj = main.Children
              .OfType<FrameworkElement>()
              .FirstOrDefault(c => "platform1".Equals(c.Tag));
  • Related