2013-04-15 29 views
4

我想從代碼隱藏(而不是TextBox的代碼隱藏,但一些父控件)中設置WPF TextBox的焦點,並在接收該焦點時從TextBox的代碼隱藏中選擇TextBox中的所有文本。如何選擇WPF文本框中的所有文本從代碼隱藏聚焦時?

我關注TextBox這樣的:

var scope = FocusManager.GetFocusScope(txt); 
FocusManager.SetFocusedElement(scope, txt); 

,聽在TextBox小號代碼隱藏在TextBox像這樣的事件:

AddHandler(GotFocusEvent, new RoutedEventHandler(SelectAllText), true); 

,並儘量選擇這樣的文字:

private static void SelectAllText(object sender, RoutedEventArgs e) 
    { 
     var textBox = e.OriginalSource as TextBox; 
     if (textBox != null) 
      textBox.SelectAll(); 
    } 

但是文本沒有得到s當選。我怎樣才能修改這個工作,因爲我喜歡它?

+0

你肯定textBox中不爲空在SelectAllText處理?設置一個斷點並逐步完成。 – Steve

+0

你說'TextBox'的代碼在後面。如果您的處理程序是實際TextBox的實例方法,那麼爲什麼不直接調用SelectAll()而不是從發件人獲取引用呢? – Steve

+0

@Steve,我檢查過/試過了。文本根據selectedText屬性進行選擇,但不會在UI中選擇,無論出於何種原因。 – Marc

回答

14

你將不得不選擇文本

實例之前設置Keyboard重點TextBox

private static void SelectAllText(object sender, RoutedEventArgs e) 
{ 
    var textBox = e.OriginalSource as TextBox; 
    if (textBox != null) 
    { 
     Keyboard.Focus(textBox); 
     textBox.SelectAll(); 
    }  
} 
相關問題