简体   繁体   English

如何循环WPF StackPanel静态项?

[英]How to loop through WPF StackPanel static Items?

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? 如何遍历StackPanel中静态声明的元素(没有数据绑定 - 在xaml中声明元素)?

Any help appreciated! 任何帮助赞赏!

Do you mean the StackPanel 's children? 你是说StackPanel的孩子吗?

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: 无论父级如何都可以使用的更通用的解决方案是使用LogicalTreeHelperVisualTreeHelper ,具体取决于您希望遍历的WPF树:

foreach (var child in LogicalTreeHelper.GetChildren(stackPanel))
{
    //do something with child
}

I thought just the same as Johnldol, since in my case I had one child and I knew its type; 我认为和Johnldol一样,因为在我的情况下,我有一个孩子,我知道它的类型; I didn't want to obscure my code by an unnecessary loop. 我不想通过不必要的循环来模糊我的代码。 So this is how I reached the TextBlock inside the Hyperlink: 这就是我在Hyperlink中到达TextBlock的方式:

        var looper = LogicalTreeHelper.GetChildren(objHyperlink).GetEnumerator();
        looper.MoveNext();
        TextBlock objTextBlock = (looper.Current as InlineUIContainer).Child as TextBlock;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM