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.
Asked
Active
Viewed 4,165 times
0
-
please check if my solution worked for you. – Akshay J Mar 17 '11 at 15:05
2 Answers
4
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);
}

Akshay J
- 5,362
- 13
- 68
- 105
-
It doesn't seem to be having a different effect to my current method. – user646265 Mar 17 '11 at 18:34
-
When I clear the textboxes, only the textboxes contained in the tab in focus are cleared. – user646265 Mar 18 '11 at 19:15
-
I've just created an array with each of the tabs in. I looped them through your function and it worked. Thanks. – user646265 Mar 19 '11 at 21:39
1
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.

Elad Katz
- 7,483
- 5
- 35
- 66