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

最新下载

热门教程

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

时间:2012-06-28 编辑:简简单单 来源:一聚教程网

程序代码

 代码如下 复制代码

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);

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

热门栏目