Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through StackPanel children in WPF

Tags:

c#

wpf

stackpanel

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);
}
like image 256
user1590636 Avatar asked Aug 01 '13 09:08

user1590636


People also ask

How do you get kids from StackPanel?

Answers. private void ChangeStyle(string buttonName) { int count = stackPanel. Children. Count; for (int itr = 0; itr < count; itr++) { if (stackPanel.

What does StackPanel do in WPF?

The StackPanel in WPF is a simple and useful layout panel. It stacks its child elements below or beside each other, dependening on its orientation. This is very useful to create any kinds of lists. All WPF ItemsControls like ComboBox , ListBox or Menu use a StackPanel as their internal layout panel.

What is the difference between StackPanel and DockPanel?

For example, the order of child elements can affect their size in a DockPanel but not in a StackPanel. This is because StackPanel measures in the direction of stacking at PositiveInfinity, whereas DockPanel measures only the available size. The following example demonstrates this key difference.

What is StackPanel?

StackPanel is a layout panel that arranges child elements into a single line that can be oriented horizontally or vertically. By default, StackPanel stacks items vertically from top to bottom in the order they are declared. You can set the Orientation property to Horizontal to stack items from left to right.


3 Answers

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

}
like image 184
Henk Holterman Avatar answered Oct 23 '22 11:10

Henk Holterman


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;
}
like image 39
Clemens Avatar answered Oct 23 '22 10:10

Clemens


Using LINQ:

foreach(var child in tab.Children.OfType<Control>)
{
    UnregisterName(child.Name);
}
like image 39
Marc Avatar answered Oct 23 '22 10:10

Marc