2012-11-25 138 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; 
    }