textbox.GotFocus 事件处理 Textbox.SelectAll() 是不行的, 这样处理会发生的情况是:
1) textbox1 当前没有焦点, 内容为 someText.
2) 鼠标点击 textbox1, 若单击点位于 someText 之内, 则 someText 被瞬间全选后所有的选择都被取消, 若单击点位于 someText 之外, 则不会发生任何事情, 没有任何选中的内容.
如下是解决办法
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); LIKE_textBox.PreviewMouseDown += new MouseButtonEventHandler(LIKE_textBox_PreviewMouseDown);//注意,这个事件的注册必须在LIKE_textBox获得焦点之前 LIKE_textBox.GotFocus += new RoutedEventHandler(LIKE_textBox_GotFocus); LIKE_textBox.LostFocus += new RoutedEventHandler(LIKE_textBox_LostFocus); } void LIKE_textBox_LostFocus(object sender, RoutedEventArgs e) { LIKE_textBox.PreviewMouseDown += new MouseButtonEventHandler(LIKE_textBox_PreviewMouseDown); } void LIKE_textBox_PreviewMouseDown(object sender, MouseButtonEventArgs e) { LIKE_textBox.Focus(); e.Handled = true; } void LIKE_textBox_GotFocus(object sender, RoutedEventArgs e) { LIKE_textBox.SelectAll(); LIKE_textBox.PreviewMouseDown -= new MouseButtonEventHandler(LIKE_textBox_PreviewMouseDown); } }
时间: 2024-10-14 14:09:54