0

Following is part of my code in Windows Forms application, how can I convert it to WPF, considering this.Controls is not available:

public Form1()
        {
            InitializeComponent();
            foreach (TextBox tb in this.Controls.OfType<TextBox>())
            {
                tb.Enter += textBox_Enter;
            }
        }

        void textBox_Enter(object sender, EventArgs e)
        {
            focusedTextbox = (TextBox)sender;
        }

private TextBox focusedTextbox = null;

private void button1_Click (object sender, EventArgs e)
        {
            if (focusedTextbox != null)
            {
                focusedTextbox.Text += "1";

            }
        }
Patrick
  • 17,669
  • 6
  • 70
  • 85
joseph
  • 353
  • 3
  • 6
  • 10
  • There may be no `Controls` property on a WPF `Window`, but you can enumerate objects with a `VisualTreeHelper` or a `LogicalTreeHelper`. With [the code in this answer](http://stackoverflow.com/a/978352/559103) you can enumerate all visible `TextBox`es with `foreach (TextBox tb in FindVisualChildren(myWindow))` – j.i.h. Jun 12 '14 at 13:58

1 Answers1

0

Listen to PreviewGotKeyboardFocus on your root element (most likely the Window itself) and record the e.NewFocus argument. Preview events bubble up the visual tree, so any control that exposes one within a parent control will trigger it (see routed events).

The event handler becomes:

    private void OnGotFocusHandler(object sender, KeyboardFocusChangedEventArgs e)
    {
        var possiblyFocusedTextbox = e.NewFocus as TextBox;
        //since we are now receiving all focus changes, the possible textbox could be null
        if (possiblyFocusedTextbox != null)
            focusedTextbox = possiblyFocusedTextbox;
    }
amnezjak
  • 2,011
  • 1
  • 14
  • 18
Mitch
  • 21,223
  • 6
  • 63
  • 86