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);
}
Answers. private void ChangeStyle(string buttonName) { int count = stackPanel. Children. Count; for (int itr = 0; itr < count; itr++) { if (stackPanel.
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.
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.
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.
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)
...
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With