程序代码
代码如下 |
复制代码 |
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);
|
所实现的功能是当第二次单击的时候,不再是全选文字,而是显示光标。