如何循环WPF StackPanel静态项?

时间:2022-09-26 09:47:22

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!

任何帮助赞赏!

2 个解决方案

#1


10  

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:

无论父级如何,更通用的解决方案是使用LogicalTreeHelper或VisualTreeHelper,具体取决于您希望遍历的WPF树:

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

#2


0  

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:

我认为和Johnldol一样,因为在我的情况下,我有一个孩子,我知道它的类型;我不想通过不必要的循环来模糊我的代码。所以这就是我在Hyperlink中到达TextBlock的方式:

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

#1


10  

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:

无论父级如何,更通用的解决方案是使用LogicalTreeHelper或VisualTreeHelper,具体取决于您希望遍历的WPF树:

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

#2


0  

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:

我认为和Johnldol一样,因为在我的情况下,我有一个孩子,我知道它的类型;我不想通过不必要的循环来模糊我的代码。所以这就是我在Hyperlink中到达TextBlock的方式:

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