How to loop through WPF StackPanel static Items?
-
07-07-2019 - |
Question
Probably very easy but I am having trouble to figure this out (also Google doesn't seem to help much).
How can I loop through the statically declared elements (no databinding - elements are declared in the xaml) of a StackPanel?
Any help appreciated!
Solution
Do you mean the StackPanel
's children?
foreach (var child in stackPanel.Children)
{
//do something with child
}
A more generic solution that would work regardless of the parent would be to use LogicalTreeHelper
or VisualTreeHelper
, depending on what WPF tree you wish to traverse:
foreach (var child in LogicalTreeHelper.GetChildren(stackPanel))
{
//do something with child
}
OTHER TIPS
I thought just the same as Johnldol, since in my case I had one child and I knew its type; I didn't want to obscure my code by an unnecessary loop. So this is how I reached the TextBlock inside the Hyperlink:
var looper = LogicalTreeHelper.GetChildren(objHyperlink).GetEnumerator();
looper.MoveNext();
TextBlock objTextBlock = (looper.Current as InlineUIContainer).Child as TextBlock;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow