1

I'm programming in c#(WPF). I have a lot of nested controls. I want to clear all of my TextBox control which are in my application. It is very hard to access them by their name. Is there any way to access them recursively and clear them?

for example some thing like this:

public void ClearAll(Control c)
{
    if(c is TextBox)
    {
        ((TextBox)c).Clear();
        return;
    }

    foreach(Control child in GetChild(c))
    {
        ClearAll(child);
    }
}
braX
  • 11,506
  • 5
  • 20
  • 33
Babak.Abad
  • 2,839
  • 10
  • 40
  • 74
  • Show your `XAML` for `TextBox` and from there it will be easier to clear them using CommandBindings or something similar. – 123 456 789 0 Apr 23 '14 at 21:20
  • 2
    you may take a look at this answer http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type – BRAHIM Kamel Apr 23 '14 at 21:21
  • Assuming these controls are bound, can you call a "reset" function on their bound objects, which could then set the text to String.Empty? – BradleyDotNET Apr 23 '14 at 21:23
  • I immigrated from WinForm to Xaml and I do'nt now about CommandBindings a lot. – Babak.Abad Apr 23 '14 at 21:23
  • Reset function? for what? how? – Babak.Abad Apr 23 '14 at 21:24
  • 1
    Rule #1 in WPF. "WPF is not WinForms"! You should probably start looking into bindings and how to set them up. You should (almost) never have to access a control by its name or manipulate it in code at all. Nearly any modification you can think of is doable through bindings. – BradleyDotNET Apr 23 '14 at 21:24
  • Are your text boxes bound? I can help if they are, or perhaps guide you on setting up those bindings otherwise. – BradleyDotNET Apr 23 '14 at 21:25
  • 1
    @Babak.Abad Now is the perfect time to learn them if you just migrated from `WinForms` :) It'll make your life easier without having to find all controls recursively and clear them one by one, instead use one command that'll clear them using commands. IMO. – 123 456 789 0 Apr 23 '14 at 21:29
  • 1
    More generally put, do some research on MVVM and how it applies to WPF. – Nathan A Apr 23 '14 at 21:45

1 Answers1

2

The VisualTreeHelper class comes handy. You can use it like this:

static public void TraverseVisualTree(Visual myMainWindow)
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(myMainWindow);
        for (int i = 0; i < childrenCount; i++)
        {
            var visualChild = (Visual)VisualTreeHelper.GetChild(myMainWindow, i);
            if (visualChild is TextBox)
            {
                TextBox tb = (TextBox)visualChild;
                tb.Clear();
            }
            TraverseVisualTree(visualChild);
        }
    }
JKO
  • 148
  • 5