user1590636 user1590636 -3 years ago 47
C# Question

Looping through StackPanel children in WPF

I have a

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

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)

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download