遍历 wpf 中静态创建的控件

Iterate through statically created controls in wpf

我正在尝试在 wpf 中迭代表单,但似乎

foreach (Control x in this.Controls) 
 { 
    if (x is TextBox) 
    {    
      do something
    } 
 }

无效!编译器无法识别 this.controls ....似乎 wpf 有所不同,但我不知道应该使用什么代码! 编辑:我不想使用 FindVisualChildren

尝试这样的事情:

        foreach (var control in MyGrid.Children.OfType<TextBox>())
        {
                //do something
        }

您不能在 Window 中遍历所有控件。你需要更具体。请注意,这只会直接获得 children 而不是 children

的 children
<Window>
   <Grid x:Name="MyGrid>
     <Button/>
     <TextBox/>
     <Label/>
   </Grid>
</Window>