-1

I want to get the Grid control that is wrapped in a border (no Name is assigned), the structure look like this:

<Grid x:Name="main">
   <uc:myUc/>
   <Border>
       <!--other elements-->
   </Border>
   <Border>
        <Grid x:Name="myGrid">
           <!--I want to get all controls here-->
        </Grid>
   </Border>
</Grid>

myUc is a user control that has a button that when clicked, I want to get all the controls inside the grid myGrid: this is the code I 'm using, it seems I should give a Name to the container Border to be able to get its children, but this is a huge change in my application.

var parent = VisualTreeHelper.GetParent(this) as UIElement;
var grid = (parent as Grid);
var chldrn = grid.Children;
foreach (var item in chldrn)
{
    var child = item;
}
//I stopped here!

Is there a way to find all descendants of an element to determie which control I take?

mm8
  • 163,881
  • 10
  • 57
  • 88
mshwf
  • 7,009
  • 12
  • 59
  • 133

1 Answers1

2

You can access any kind of child in containers by their type

XAML Example:

<Grid x:Name="myGrid">
    <Button Content="Button1"></Button>
    <Button Content="Button2"></Button>
    <CheckBox Content="CheckBox1"></CheckBox>
</Grid>

C# Example

private void Button_Click(object sender, RoutedEventArgs e)
{
    foreach(var Child in myGrid.Children.OfType<Button>()) // this will only get buttons in grid's children
    {
        MessageBox.Show(Child.Content);
    }

    //another way:

    foreach(var Child in myGrid.Children)
    {
        if (Child is CheckBox)
        {
            var checkBox = (CheckBox)Child;
            checkBox.IsChecked = true;
        }
    }
}
Mohamad Rashidi
  • 307
  • 2
  • 14