Reputation: 1068
i want to Know the x:Name of the Grid child as in this case :
<Grid x:Name="one" Grid.Row="0" Margin="49.667,15,15,15">
<Grid x:Name="container1" Background="Red" Margin="10"/>
</Grid>
<Button Content="mov" Foreground="White" x:Name="first" HorizontalAlignment="Left" Margin="8,44.833,0,70.167" Width="29.334" Background="Black" Click="first_Click"/>
and here the code when i click :
private void first_Click(object sender, System.Windows.RoutedEventArgs e)
{
var ttt = FindVisualChild<Grid>(one);
MessageBox.Show(ttt.ToString());
}
private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
When i click the message just show this content "System.Window.Controls.Grid" instead i want to know the x:name in this case "container1" then i ask kindly if you have any suggestion that i can receive the x:Name of the Grid.
Thank you in advance.
Sincerely
Upvotes: 0
Views: 2221
Reputation: 7414
Credit goes to dkozl for providing you the answer in the comments of the OP. I wanted to give a bit of additional information to supplement it.
Any element that is exposed to you within the XAML can be accessed in the code-behind as a property (there are some exceptions but for the most part this rings true).
<Grid x:Name="one" Grid.Row="0" Margin="49.667,15,15,15">
<Grid x:Name="container1" Background="Red" Margin="10"/>
</Grid>
<Button Content="mov" Foreground="White" x:Name="first" HorizontalAlignment="Left" Margin="8,44.833,0,70.167" Width="29.334" Background="Black" Click="first_Click"/>
If you wanted to, you can access the Grid properties like
private void first_Click(object sender, System.Windows.RoutedEventArgs e)
{
this.one.Background = Brushes.Yellow;
this.one.Margin = new Thickness(0, 5, 10, 25);
}
You also do not need to use the visual tree lookup since you have provided a name to the grid, providing the code-behind is associated with the view that holds the two grids.
You can just do:
private void first_Click(object sender, System.Windows.RoutedEventArgs e)
{
MessageBox.Show(this.container1.Name);
}
Upvotes: 1