I have a Listbox, which houses some items. The Items are Grids which house a variety of Textblocks, buttons, etc etc.
foreach (Grid thisGrid in myListBox.SelectedItems)
{
foreach (TextBlock thisTextblock in thisGrid.Children)
{
//Do Somthing
}
}
Yet this throws an exception because there are other items than Textblock's in there. How can I accomodate this? Thanks.
As I read it, the problem here is with the inner loop, and there being things in Children
that are not TextBlock
s.
If LINQ is available:
foreach (TextBlock thisTextblock in thisGrid.Children.OfType<TextBlock>()) {
// ... do something here
}
otherwise:
foreach (object child in thisGrid.Children) {
TextBlock thisTextblock = child as TextBlock;
if(thisTextblock == null) continue;
// ... do something here
}
you could try
foreach (TextBlock thisTextblock in thisGrid.Children.Where(c => c is TextBlock))
{ /* ... */ }
for your inner loop.
EDIT: TIL, that this can also be written as:
foreach (TextBlock in thisTextblock in thisGrid.Children.OfType<TextBlock>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With