How to go through all the controls of a WPF window?

Asked

Viewed 310 times

4

Is there any way I can go through all the controls of a window and disable them? For example, do a foreach that disables one by one of the controls. Something like below, only for WPF, and not Winforms.

private void HabilitarControles(bool habilita)
    {
        foreach (Control c in Controls)
        {
            c.Enabled = habilita;
            foreach (Control con in c.Controls.OfType<Control>())
                con.Enabled = habilita;
        }
    }

1 answer

4


You don’t have to do this one by one. You probably put them inside a Panel (if it does not, it should), disable only the Panel. All will be disabled.

If you still insist on doing what you already know how to do:

private void HabilitarControles(bool habilita) => foreach (var c in this.Controls) c.Enabled = habilita;

I put in the Github for future reference.

If you want some other sophistication just adapt this. There are no other requirements in the question.

  • My controls are all on a grid. If I try to use this method, I get the error: "The name 'Controls' does not exist in the Current context"

  • 2

    I’ve changed and I think it will. When it’s like that, you have to ask the question. We have no way of guessing the problems you’re having. But anyway, disable the GridPanel, is easier.

  • Actually, disabling Grid is better. However, even using this in the code, it does not recognize Controls.

  • Without a bigger context it’s hard to help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.