15

I have a StackPanel that is full of controls, I am trying to loop through the elements and get their Names, but it seems that I need to cast each element to its type in order to access its Name property.

But what if I have a lot of different types in the StackPanel and I just want to get the elements name?

Is there a better way to do that?

Here is what I've tried:

foreach (object child in tab.Children)
{
    UnregisterName(child.Name);
}
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
user1590636
  • 1,174
  • 6
  • 26
  • 56

3 Answers3

25

It should be enough to cast to the right base class. Everything that descends from FrameworkElement has a Name property.

foreach(object child in tab.Children)
{
   string childname = null;
   if (child is FrameworkElement )
   {
     childname = (child as FrameworkElement).Name;
   }

   if (childname != null)
      ...

}
H H
  • 263,252
  • 30
  • 330
  • 514
  • How about `childname = (child as FrameworkElement)?.Name;`? – default Jun 13 '17 at 07:20
  • This is an answer from 2013, no `?.` yet. I'm not going to retrofit that everywhere. And I'm not sure if it's always better, here `((FrameworkElement)child).Name` might be the most optimized form. – H H Jun 13 '17 at 07:23
  • Yeah, I figured since you were editing the answer anyways. I saw the date. – default Jun 13 '17 at 07:25
9

You may just use the appropriate type for the foreach loop variable:

foreach (FrameworkElement element in panel.Children)
{
    var name = element.Name;
}

This works as long as there are only FrameworkElement derived controls in the Panel. If there are also others (like derived from UIElement only) you may write this:

using System.Linq;
...
foreach (var element in panel.Children.OfType<FrameworkElement>())
{
    var name = element.Name;
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
2

Using LINQ:

foreach(var child in tab.Children.OfType<Control>)
{
    UnregisterName(child.Name);
}
Marc
  • 12,706
  • 7
  • 61
  • 97