Looping through StackPanel children in WPF

user1590636 picture user1590636 · Aug 1, 2013 · Viewed 23.5k times · Source

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);
}

Answer

Henk Holterman picture Henk Holterman · Aug 1, 2013

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)
      ...

}