wpf中textbox控件属性_WPF中TextBox控件对于鼠标单击获取焦点后的全选

更新时间:2017-08-10    来源:WPF    手机版     字体:

【www.bbyears.com--WPF】

程序代码

 代码如下

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

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

本文来源:http://www.bbyears.com/asp/34743.html