GotFocus和PreviewLeftButtonDown事件

当TextBox获得焦点后,其中的文字会被全选。通过GotFocus和PreviewLeftButtonDown事件,就可以模拟上述行为。

如果用户只是用键盘操作,GotFocus事件就足够了。

如果使用鼠标操作,就要用到2个事件了。TextBox会将光标放在鼠标单击的那个位置。为了防止这种情况,会实现PreviewLeftButtonDown事件,

在该控件获得焦点后,将该事件的Handled属性设置为true。这会终止该事件,从而防止光标被定位到TextBox中的特定位置。

private void timeAllowedTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            timeAllowedTextBox.SelectAll();
        }

        private void timeAllowedTextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var control = sender as TextBox;
            if (control == null)
                return;

            Keyboard.Focus(control);
            e.Handled = true;
        }

 

posted @ 2014-11-04 22:58  韭菜笔记本  阅读(730)  评论(0编辑  收藏  举报