Quote through StackPanel in WPF

I have a StackPanel that is filled with controls, I try to skip the elements and get their names, but it seems to me that I need to give each element its type in order to access the Name property.

But what if I have many different types in the StackPanel and I just want to get the name of the element?

Is there a better way to do this?

Here is what I tried:

 foreach (object child in tab.Children) { UnregisterName(child.Name); } 
+8
c # wpf stackpanel
source share
3 answers

This should be enough to translate it into the right base class. Everything that comes 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) ... } 
+15
source share

You can simply use the appropriate type for the foreach loop variable:

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

This works as long as the panel has only FrameworkElement tags. If there are others (e.g. derivatives of UIElement ), you can write this:

 using System.Linq; ... foreach (var element in panel.Children.OfType<FrameworkElement>()) { var name = element.Name; } 
+7
source share

Using LINQ:

 foreach(var child in tab.Children.OfType<Control>) { UnregisterName(child.Name); } 
+2
source share

All Articles