WPF中TextBox控件对于鼠标单击获取焦点后的全选
1 void OnLostFocus(object sender, RoutedEventArgs e) 2 { 3 TextBox tb = e.Source as TextBox; 4 tb.PreviewMouseDown += new MouseButtonEventHandler(OnPreviewMouseDown); 5 } 6 7 void OnPreviewMouseDown(object sender, MouseButtonEventArgs e) 8 { 9 TextBox tb = e.Source as TextBox; 10 tb.Focus(); 11 e.Handled = true; 12 } 13 14 void OnGotFocus(object sender, RoutedEventArgs e) 15 { 16 TextBox tb = e.Source as TextBox; 17 tb.SelectAll(); 18 tb.PreviewMouseDown -= new MouseButtonEventHandler(OnPreviewMouseDown); 19 }
<TextBox Name="searchTextBox" Background="DarkOrange" HorizontalAlignment="Stretch" MaxLength="15" TextAlignment ="Center" TextChanged="OnSearchTextChange" GotFocus="OnGotFocus" PreviewMouseDown="OnPreviewMouseDown" LostFocus="OnLostFocus"> 输入名称搜索
</TextBox>
关键点在于鼠标按下之时
tb.Focus(); e.Handled = true;
由这里引发GotFocus事件 并且设置Handled 标记阻止路由事件继续传播
在GotFocus的事件里面利用tb.SelectAll()全选
tb.PreviewMouseDown -= new MouseButtonEventHandler(OnPreviewMouseDown);
所实现的功能是当第二次单击的时候,不再是全选文字,而是显示光标。
第一次发博文,欢迎指正。