0

以下是我在 Windows 窗体应用程序中的代码的一部分,我如何将其转换为 WPF,考虑到this.Controls不可用:

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";

            }
        }
4

1 回答 1

0

聆听PreviewGotKeyboardFocus您的根元素(很可能是 Window 本身)并记录e.NewFocus参数。预览事件在可视化树中冒泡,因此任何在父控件中公开事件的控件都会触发它(请参阅路由事件)。

事件处理程序变为:

    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;
    }
于 2012-11-25T04:51:16.170 回答