Question

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);
}
Was it helpful?

Solution

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

}

OTHER TIPS

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

Using LINQ:

foreach(var child in tab.Children.OfType<Control>)
{
    UnregisterName(child.Name);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top