如果我从GotFocus事件处理程序中调用SelectAll,它对鼠标不起作用——鼠标一释放,选择就消失了。
编辑:人们喜欢唐纳利的回答,我将试着解释为什么我不像公认的答案那样喜欢它。
It is more complex, while the accepted answer does the same thing in a simpler way.
The usability of accepted answer is better. When you click in the middle of the text, text gets unselected when you release the mouse allowing you to start editing instantly, and if you still want to select all, just press the button again and this time it will not unselect on release. Following Donelle's recipe, if I click in the middle of text, I have to click second time to be able to edit. If I click somewhere within the text versus outside of the text, this most probably means I want to start editing instead of overwriting everything.
不知道为什么它在GotFocus事件中失去了选择。
但是一个解决方案是在GotKeyboardFocus和GotMouseCapture事件上进行选择。这样它就能一直工作。
——编辑——
在这里添加一个例子来告诉人们如何解决上面提到的一些缺点:
private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
// Fixes issue when clicking cut/copy/paste in context menu
if (textBox.SelectionLength == 0)
textBox.SelectAll();
}
private void TextBox_LostMouseCapture(object sender, MouseEventArgs e)
{
// If user highlights some text, don't override it
if (textBox.SelectionLength == 0)
textBox.SelectAll();
// further clicks will not select all
textBox.LostMouseCapture -= TextBox_LostMouseCapture;
}
private void TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
// once we've left the TextBox, return the select all behavior
textBox.LostMouseCapture += TextBox_LostMouseCapture;
}
我也有同样的问题。在VB。Net的工作方式很简单:
VB
XAML:
<TextBox x:Name="txtFilterFrequency" />
Codehind:
Private Sub txtFilterText_GotFocus(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles txtFilterText.GotFocus
Me.Dispatcher.BeginInvoke(Sub()
txtFilterText.SelectAll()
End Sub, DispatcherPriority.ApplicationIdle, Nothing)
End Sub
c#(感谢ViRuSTriNiTy)
private delegate void TextBoxSelectAllDelegate(object sender);
private void TextBoxSelectAll(object sender)
{
(sender as System.Windows.Controls.TextBox).SelectAll();
}
private void MyTextBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
TextBoxSelectAllDelegate d = TextBoxSelectAll;
this.Dispatcher.BeginInvoke(d,
System.Windows.Threading.DispatcherPriority.ApplicationIdle, sender);
}
从这里开始:
在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();
}