以下是我在 Windows 窗体应用程序中的代码的一部分,考虑到this.Controls
不可用,如何将其转换为 WPF:
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";
}
}
监听根
元素(很可能是窗口本身)上的PreviewGotKeyboardFocus
并记录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;
}