一聚教程网:一个值得你收藏的教程网站

最新下载

WPF中TextBox控件对于鼠标单击获取焦点后的全选

时间:2012-06-28 00:00:00 编辑:简简单单 来源:转载

程序代码

 代码如下

void OnLostFocus(object sender, RoutedEventArgs e)
         {
             TextBox tb = e.Source as TextBox;
             tb.PreviewMouseDown += new MouseButtonEventHandler(OnPreviewMouseDown);
         }
 
         void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
         {
             TextBox tb = e.Source as TextBox;
             tb.Focus();
             e.Handled = true;
         }
 
         void OnGotFocus(object sender, RoutedEventArgs e)
         {
             TextBox tb = e.Source as TextBox;
             tb.SelectAll();
             tb.PreviewMouseDown -= new MouseButtonEventHandler(OnPreviewMouseDown);
         }

 

TextBox Name="searchTextBox" Background="DarkOrange" HorizontalAlignment="Stretch" MaxLength="15" TextAlignment ="Center"
     TextChanged="OnSearchTextChange" GotFocus="OnGotFocus" PreviewMouseDown="OnPreviewMouseDown" LostFocus="OnLostFocus">


 

输入名称搜索  关键点在于鼠标按下之时

 代码如下
tb.Focus();
e.Handled = true;

由这里引发GotFocus事件 并且设置Handled 标记阻止路由事件继续传播

在GotFocus的事件里面利用tb.SelectAll()全选

 代码如下

tb.PreviewMouseDown -= new MouseButtonEventHandler(OnPreviewMouseDown);

所实现的功能是当第二次单击的时候,不再是全选文字,而是显示光标。

网站留言

热门栏目