以下是我在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";
}
}
答案 0 :(得分:0)
在你的根元素(很可能是Window本身)上收听PreviewGotKeyboardFocus
并记录e.NewFocus
参数。预览事件会冒泡出可视树,因此任何在父控件中公开一个控件的控件都会触发它(请参阅routed events)。
事件处理程序变为:
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;
}