當TextBox獲得焦點后,其中的文字會被全選。通過GotFocus和PreviewLeftButtonDown事件,就可以模擬上述行為。
如果用戶只是用鍵盤操作,GotFocus事件就足夠了。
如果使用鼠標操作,就要用到2個事件了。TextBox會將光標放在鼠標單擊的那個位置。為了防止這種情況,會實現PreviewLeftButtonDown事件,
在該控件獲得焦點后,將該事件的Handled屬性設置為true。這會終止該事件,從而防止光標被定位到TextBox中的特定位置。
private void timeAllowedTextBox_GotFocus(object sender, RoutedEventArgs e){timeAllowedTextBox.SelectAll();}private void timeAllowedTextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e){var control = sender as TextBox;if (control == null)return;Keyboard.Focus(control);e.Handled = true;}
?