C#,Foreach项目

tur*_*wer 4 .net c# silverlight

我有一个列表框,其中包含一些项目.这些项目是网格,包含各种文本块,按钮等.

foreach (Grid thisGrid in myListBox.SelectedItems)
                        {
                                foreach (TextBlock thisTextblock in thisGrid.Children)
                                {
                                     //Do Somthing
                                }
                        }
Run Code Online (Sandbox Code Playgroud)

然而,这引发了一个例外,因为除了Textblock之外还有其他项目.我怎么能适应这个?谢谢.

Mar*_*ell 13

当我读到它时,这里的问题是内部循环,并且存在的东西Children不是TextBlocks.

如果LINQ可用:

foreach (TextBlock thisTextblock in thisGrid.Children.OfType<TextBlock>()) {
    // ... do something here
}
Run Code Online (Sandbox Code Playgroud)

除此以外:

foreach (object child in thisGrid.Children) {
    TextBlock thisTextblock = child as TextBlock;
    if(thisTextblock  == null) continue;
    // ... do something here
}
Run Code Online (Sandbox Code Playgroud)