Search code examples
c#wpftextboxwpf-controls

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.


Solution

  • 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);
    }