0

So I have a user control with six textboxes and a few buttons. One of those buttons is 'clear'. When I click the clear button, in the btnClear_Click handler, I want to find all the textboxes in my user control (and ONLY in my user control). And then set them to an empty string. That's it. That's all.

This is turning out to be a herculean, insurmountably difficult thing to do. Finding an answer is like trying to map the human genome. I just want to ITERATE THROUGH THE CONTROLS. Nothing more.

I'm not interested in hearing about the merits of what I'm trying to do. Just the mechanics of how to do it. Something like this:

public partial class myUserControl: UserControl
{
    private void btnClear_Click(object sender, RoutedEventArgs e)
    {
        var allMyControls = SomeMiraculousOperationToGetAllControlsThatOnlyExistInMyUserControl();
        foreach (var control in allMyControls)
        {
            if (control is TextBox)
                ((TextBox)control).Text = string.Empty;
        }
    }
}
Kerry Thomas
  • 119
  • 6

1 Answers1

0

You can use the VisualTreeHelper to enumerate the child controls of your user control.

You can find an extension method base on this class here

public static T GetChildOfType<T>(this DependencyObject depObj) 
    where T : DependencyObject
{
    if (depObj == null) return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null) return result;
    }
    return null;
}
Maxwell77
  • 918
  • 6
  • 16