Reputation: 85
Hello i have an user control and i need all the textbox , buttons, etc from this user control This there a way that i have all this elements? Thanks
Upvotes: 2
Views: 1890
Reputation: 7146
BrokenGlass's method works for sure, but it's a bit obtuse. Here is a simplified way of doing it:
When you create a control in VisualStudio or Blend, generally you're going to get a UserControl with a grid inside.
<UserControl x:Class="RHooligan"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid x:Name="RootElement>
</Grid>
Assuming your UserControl's Root element is a container control (Grid,StackPanel,Canvas, etc) and you've named it RootElement, you can do this to iterate through it's children.
foreach(FrameworkElement element in RootElement.Children)
{
//do something with element
//////////////////////////
}
Upvotes: 1
Reputation: 160952
you can use the VisualTreeHelper to achieve this.
There's an article here that offers the following extension method to help:
public static IEnumerable<DependencyObject> GetVisuals(this DependencyObject root)
{
int count = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(root, i);
yield return child;
foreach (var descendants in child.GetVisuals())
{
yield return descendants;
}
}
}
You can then do the following:
foreach (var control in LayoutRoot.GetVisuals().OfType<Control>())
{
//handle control of type <Control>
}
Upvotes: 4