问题
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!
回答1:
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
}
回答2:
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;
来源:https://stackoverflow.com/questions/1420763/how-to-loop-through-wpf-stackpanel-static-items