user646265
user646265

Reputation: 1031

WPF - clear all textboxes in tabcontrol not working

I have an application with a tab control and several textboxes in each tab and when the user says so, I would like every text box in the window (called MainWindow) to be cleared. I used the method described here, but it only seems to work for the textboxes in the tab that it is in focus.

Upvotes: 0

Views: 4185

Answers (2)

Akshay J
Akshay J

Reputation: 5468

Try this:

void ClearTextBoxes(DependencyObject obj)
{
    TextBox tb = obj as TextBox;
    if (tb != null)
        tb.Text = "";

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj as DependencyObject); i++)
        ClearTextBoxes(VisualTreeHelper.GetChild(obj, i));
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    ClearTextBoxes(this);
}

Upvotes: 4

Elad Katz
Elad Katz

Reputation: 7601

Try replace calls to VisualTreeHelper.GetChildren with LogicalTreeHelper.GetChildren

LogicalTreeHelper gets the actual visual tree. usually this is way more than the logical tree, but in this case since the other tabs are not visible - the visual sub-tree in those tabs doesn't get created. The LogicalTree should still be there though, so that should work.

Upvotes: 1

Related Questions