【WPF】獲取焦點全部選中事件
阿新 • • 發佈:2019-01-13
效果
功能
當TextBox獲取焦點時,如TextBox中有內容,則預設全部選中
程式碼
public AddTaskWindow() { InitializeComponent(); //在文字框獲取焦點時,要求其中內容全部選中 txtContent.PreviewMouseDown += new MouseButtonEventHandler(txtContent_PreviewMouseDown); txtContent.GotFocus += new RoutedEventHandler(txtContent_GotFocus); txtContent.LostFocus += new RoutedEventHandler(txtContent_LostFocus); } /// <summary> /// 番茄名稱,獲取焦點 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtContent_GotFocus(object sender, RoutedEventArgs e) { txtContent.SelectAll();//全選 txtContent.PreviewMouseDown -= new MouseButtonEventHandler(txtContent_PreviewMouseDown); } /// 番茄名稱,失去焦點 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtContent_LostFocus(object sender, RoutedEventArgs e) { txtContent.PreviewMouseDown += new MouseButtonEventHandler(txtContent_PreviewMouseDown); } /// <summary> /// 番茄名稱,單擊事件前 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtContent_PreviewMouseDown(object sender, MouseButtonEventArgs e) { txtContent.Focus(); e.Handled = true; }