How to loop through WPF StackPanel static Items?

旧城冷巷雨未停 提交于 2019-12-23 08:07:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!