WPF Tips-当tab键获得焦点时textbox 全选

如果值有单独的一两个textbox,可以对GotKeyboardFocus事件处理为SelectAll()。

<TextBox GotKeyboardFocus="SelectAllText"/>
private void SelectAllText(object sender, RoutedEventArgs e)
{
    TextBox tb = sender as TextBox;
    if(tb!=null)
    {
        tb.SelectAll();
    }    
}

 

但当工程中textbox数量比较多时,可以在App.xaml.cs中进行事件注册:

 

protected override void OnStartup(StartupEventArgs e)
        {
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));

            base.OnStartup(e);
        }

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            (sender as TextBox).SelectAll();
        }

 

参考:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/564b5731-af8a-49bf-b297-6d179615819f/how-to-selectall-in-textbox-when-textbox-gets-focus-by-mouse-click?forum=wpf

http://madprops.org/blog/wpf-textbox-selectall-on-focus/

 

posted @ 2017-06-05 10:26  Jane&Coding  阅读(1462)  评论(0)    收藏  举报