WPF TextBox select 全部位于 Tab 焦点上
WPF TextBox select all on Tab focus
我正在尝试 select 使用 Tab 键 完成焦点后的所有文本。但我无法找到正确的解决方案。现在我正在使用 GotFocusEvent 但现在当我用鼠标单击时它会引发事件。
我现在使用的代码是:
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText));
void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
textBox.SelectAll();
}
使用MouseButtonState
如下:
void SelectAllText(object sender, RoutedEventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Released)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
textBox.SelectAll();
}
}
参考这个答案
Textbox SelectAll on tab but not mouse click
您可以修改为...
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnGotKeyboardFocus));
void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null && !textBox.IsReadOnly && e.KeyboardDevice.IsKeyDown(Key.Tab))
textBox.SelectAll();
}
您还应注意有关在 LostKeyboardFocus
上清除选择的详细信息
我正在尝试 select 使用 Tab 键 完成焦点后的所有文本。但我无法找到正确的解决方案。现在我正在使用 GotFocusEvent 但现在当我用鼠标单击时它会引发事件。
我现在使用的代码是:
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText));
void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
textBox.SelectAll();
}
使用MouseButtonState
如下:
void SelectAllText(object sender, RoutedEventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Released)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
textBox.SelectAll();
}
}
参考这个答案
Textbox SelectAll on tab but not mouse click
您可以修改为...
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnGotKeyboardFocus));
void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null && !textBox.IsReadOnly && e.KeyboardDevice.IsKeyDown(Key.Tab))
textBox.SelectAll();
}
您还应注意有关在 LostKeyboardFocus