2012-11-25 110 views
0

以下是我在Windows窗体应用程序,我怎样才能将其转换为WPF,考虑this.Controls代码部分不可用:转换Windows窗体到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"; 

      } 
     } 
+2

什么是WFA ...... –

+0

Windows窗体应用程序 –

+0

可能没有'在WPF'Window' Controls'属性,但您可以枚举对象?用一个'VisualTreeHelper'或一个'LogicalTreeHelper'。用[这个答案中的代码](http://stackoverflow.com/a/978352/559103),你可以用'foreach(FindVisualChildren (myWindow))中的TextBox tb枚举所有可见的'TextBox''' –

回答

0

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