如何自动select焦点在WPF文本框中的所有文本?

如果我从GotFocus事件处理程序中调用SelectAll ,则不能使用鼠标 – 只要释放鼠标,select就会消失。

编辑:人们喜欢Donnelle的答案,我会尽力解释为什么我不喜欢它接受的答案。

  • 这是比较复杂的,而被接受的答案以更简单的方式来做同样的事情。
  • 接受答案的可用性比较好。 当你在文本中间点击时,释放鼠标时文本会被取消select,让你立即开始编辑,如果你仍然想要全部select,只需再次按下button,这次在释放时不会取消select。 按照Donelle的配方,如果我点击文本中间,我必须点击第二次才能编辑。 如果我在文本内部与文本之外的地方点击,这很可能意味着我要开始编辑而不是覆盖所有内容。

不知道为什么它在GotFocus事件中失去了select。

但是一个解决scheme是在GotKeyboardFocus和GotMouseCapture事件上进行select。 这样它将永远工作。

我们有它,所以第一次点击select所有,另一个点击进入光标(我们的应用程序是专为笔使用平板电脑)。

你可能会觉得它很有用。

 public class ClickSelectTextBox : TextBox { public ClickSelectTextBox() { AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyIgnoreMouseButton), true); AddHandler(GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText), true); AddHandler(MouseDoubleClickEvent, new RoutedEventHandler(SelectAllText), true); } private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { // Find the TextBox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); if (parent != null) { var textBox = (TextBox)parent; if (!textBox.IsKeyboardFocusWithin) { // If the text box is not yet focussed, give it the focus and // stop further processing of this click event. textBox.Focus(); e.Handled = true; } } } private static void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } } 

唐纳尔的答案是最好的,但不得不派上一个新的class级来使用它是一个痛苦。

而不是我注册处理程序App.xaml.cs中的应用程序中的所有文本框的处理程序。 这允许我使用标准TextBox控件的Donnelle答案。

将以下方法添加到您的App.xaml.cs中:

 public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { // Select the text in a TextBox when it receives focus. EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyIgnoreMouseButton)); EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText)); EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent, new RoutedEventHandler(SelectAllText)); base.OnStartup(e); } void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { // Find the TextBox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); if (parent != null) { var textBox = (TextBox)parent; if (!textBox.IsKeyboardFocusWithin) { // If the text box is not yet focused, give it the focus and // stop further processing of this click event. textBox.Focus(); e.Handled = true; } } } void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } } 

这是相当老,但我会显示我的答案无论如何。
我select了Donnelle的部分答案(跳过了双击),因为我认为这对用户来说是最less的惊喜。 然而,像gcores我不喜欢创build派生类的需要。 但是我也不喜欢“启动…”方法。 我需要这个“一般但不总是”的基础。

我已经实现这个作为附加的依赖项属性,所以我可以在xaml中设置SelectTextOnFocus.Active=True 。 我觉得这是最令人愉快的。

 namespace foo.styles.behaviour { using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; public class SelectTextOnFocus : DependencyObject { public static readonly DependencyProperty ActiveProperty = DependencyProperty.RegisterAttached( "Active", typeof(bool), typeof(SelectTextOnFocus), new PropertyMetadata(false, ActivePropertyChanged)); private static void ActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TextBox) { TextBox textBox = d as TextBox; if ((e.NewValue as bool?).GetValueOrDefault(false)) { textBox.GotKeyboardFocus += OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown; } else { textBox.GotKeyboardFocus -= OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDown; } } } private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DependencyObject dependencyObject = GetParentFromVisualTree(e.OriginalSource); if (dependencyObject == null) { return; } var textBox = (TextBox)dependencyObject; if (!textBox.IsKeyboardFocusWithin) { textBox.Focus(); e.Handled = true; } } private static DependencyObject GetParentFromVisualTree(object source) { DependencyObject parent = source as UIElement; while (parent != null && !(parent is TextBox)) { parent = VisualTreeHelper.GetParent(parent); } return parent; } private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) { TextBox textBox = e.OriginalSource as TextBox; if (textBox != null) { textBox.SelectAll(); } } [AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)] [AttachedPropertyBrowsableForType(typeof(TextBox))] public static bool GetActive(DependencyObject @object) { return (bool) @object.GetValue(ActiveProperty); } public static void SetActive(DependencyObject @object, bool value) { @object.SetValue(ActiveProperty, value); } } } 

对于我的“一般而非总是”特性,我把这个属性设置为True(全局)TextBox-Style。 这种“select文本”的方式总是“打开”,但我可以在每个文本框的基础上禁用它。

为了您的方便,以下是实现答案解决scheme的Blend行为:

一个用于附加到单个文本框:

 public class SelectAllTextOnFocusBehavior : Behavior<TextBox> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.GotKeyboardFocus += AssociatedObjectGotKeyboardFocus; AssociatedObject.GotMouseCapture += AssociatedObjectGotMouseCapture; AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObjectPreviewMouseLeftButtonDown; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.GotKeyboardFocus -= AssociatedObjectGotKeyboardFocus; AssociatedObject.GotMouseCapture -= AssociatedObjectGotMouseCapture; AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObjectPreviewMouseLeftButtonDown; } private void AssociatedObjectGotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { AssociatedObject.SelectAll(); } private void AssociatedObjectGotMouseCapture(object sender, System.Windows.Input.MouseEventArgs e) { AssociatedObject.SelectAll(); } private void AssociatedObjectPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if(!AssociatedObject.IsKeyboardFocusWithin) { AssociatedObject.Focus(); e.Handled = true; } } } 

而一个用于附加到包含多个文本框的容器的根目录:

 public class SelectAllTextOnFocusMultiBehavior : Behavior<UIElement> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.GotKeyboardFocus += HandleKeyboardFocus; AssociatedObject.GotMouseCapture += HandleMouseCapture; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.GotKeyboardFocus -= HandleKeyboardFocus; AssociatedObject.GotMouseCapture -= HandleMouseCapture; } private static void HandleKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { var txt = e.NewFocus as TextBox; if (txt != null) txt.SelectAll(); } private static void HandleMouseCapture(object sender, System.Windows.Input.MouseEventArgs e) { var txt = e.OriginalSource as TextBox; if (txt != null) txt.SelectAll(); } } 

这是MSDN上非常好的一个非常简单的解决scheme:

 <TextBox MouseDoubleClick="SelectAddress" GotKeyboardFocus="SelectAddress" PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" /> 

这是后面的代码:

 private void SelectAddress(object sender, RoutedEventArgs e) { TextBox tb = (sender as TextBox); if (tb != null) { tb.SelectAll(); } } private void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { TextBox tb = (sender as TextBox); if (tb != null) { if (!tb.IsKeyboardFocusWithin) { e.Handled = true; tb.Focus(); } } } 

虽然这是一个老问题,但我刚刚遇到了这个问题,但是使用附加行为解决了这个问题,而不是像谢尔盖的回答那样expression行为。 这意味着我不需要依赖于Blend SDK中的System.Windows.Interactivity

 public class TextBoxBehavior { public static bool GetSelectAllTextOnFocus(TextBox textBox) { return (bool)textBox.GetValue(SelectAllTextOnFocusProperty); } public static void SetSelectAllTextOnFocus(TextBox textBox, bool value) { textBox.SetValue(SelectAllTextOnFocusProperty, value); } public static readonly DependencyProperty SelectAllTextOnFocusProperty = DependencyProperty.RegisterAttached( "SelectAllTextOnFocus", typeof (bool), typeof (TextBoxBehavior), new UIPropertyMetadata(false, OnSelectAllTextOnFocusChanged)); private static void OnSelectAllTextOnFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var textBox = d as TextBox; if (textBox == null) return; if (e.NewValue is bool == false) return; if ((bool) e.NewValue) { textBox.GotFocus += SelectAll; textBox.PreviewMouseDown += IgnoreMouseButton; } else { textBox.GotFocus -= SelectAll; textBox.PreviewMouseDown -= IgnoreMouseButton; } } private static void SelectAll(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox == null) return; textBox.SelectAll(); } private static void IgnoreMouseButton(object sender, System.Windows.Input.MouseButtonEventArgs e) { var textBox = sender as TextBox; if (textBox == null || textBox.IsKeyboardFocusWithin) return; e.Handled = true; textBox.Focus(); } } 

然后你可以像这样在你的XAML中使用它:

 <TextBox Text="Some Text" behaviors:TextBoxBehavior.SelectAllTextOnFocus="True"/> 

我在这里博客了。

我认为这个效果很好:

 private void ValueText_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = (TextBox)e.OriginalSource; tb.Dispatcher.BeginInvoke( new Action(delegate { tb.SelectAll(); }), System.Windows.Threading.DispatcherPriority.Input); } 

如果你想实现它作为扩展方法:

 public static void SelectAllText(this System.Windows.Controls.TextBox tb) { tb.Dispatcher.BeginInvoke( new Action(delegate { tb.SelectAll(); }), System.Windows.Threading.DispatcherPriority.Input); } 

在您的GotFocus活动中:

 private void ValueText_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = (TextBox)e.OriginalSource; tb.SelectAllText(); } 

我发现上面的解决scheme,因为几个月前我正在寻找一种方法来设置一个给定的UIElement焦点。 我发现下面的代码(特此给出信用),它运作良好。 即使它与OP的问题没有直接关系,我也会发布它,因为它演示了使用Dispatcher与UIElement一起使用的相同模式。

 // Sets focus to uiElement public static void DelayedFocus(this UIElement uiElement) { uiElement.Dispatcher.BeginInvoke( new Action(delegate { uiElement.Focusable = true; uiElement.Focus(); Keyboard.Focus(uiElement); }), DispatcherPriority.Render); } 

我发现这里提供的答案没有模仿一个标准的Windows文本框。 例如,尝试单击文本框的最后一个字符和文本框右侧之间的空白处。 这里的大多数解决scheme总是select整个内容,这使得向文本框添加文本非常困难。

我在这里的答案在这方面performance得更好。 这是一个行为(所以它需要Blend SDK中的System.Windows.Interactivity程序集)。 它也可以使用附加属性重写。

 public sealed class SelectAllTextOnFocusBehavior : Behavior<TextBox> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObject_PreviewMouseLeftButtonDown; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObject_PreviewMouseLeftButtonDown; } void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // Find the textbox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); var textBox = parent as TextBox; Debug.Assert(textBox != null); if (textBox.IsFocused) return; textBox.SelectAll(); Keyboard.Focus(textBox); e.Handled = true; } } 

这是基于我在这里find的代码。

这个简单的实现对我来说是完美的:

 void TextBox_GotFocus(object sender, RoutedEventArgs e) { ((TextBox) sender).SelectAll(); } void TextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e) { var TextBox = (TextBox) sender; if (!TextBox.IsKeyboardFocusWithin) { TextBox.Focus(); e.Handled = true; } } 

要将其应用于所有TextBox ,请在InitializeComponent();后面放置以下代码InitializeComponent();

 EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus)); EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseDownEvent, new MouseButtonEventHandler(TextBox_PreviewMouseDown)); 

在App.xaml文件中

 <Application.Resources> <Style TargetType="TextBox"> <EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/> </Style> </Application.Resources> 

在App.xaml.cs文件中

 private void TextBox_GotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e) { ((TextBox)sender).SelectAll(); } 

使用此代码,您可以访问应用程序中的所有文本框。

采取从这里 :

在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(); } 

我有一个简单的答案(只有PreviewMouseLeftButtonDown事件),它似乎模仿浏览器的常用function:

在xaml中你有一个文本框说:

 <TextBox Text="http://www.blabla.com" BorderThickness="2" BorderBrush="Green" VerticalAlignment="Center" Height="25" PreviewMouseLeftButtonDown="SelectAll" /> 

在代码隐藏中:

 private void SelectAll(object sender, MouseButtonEventArgs e) { TextBox tb = (sender as TextBox); if (tb == null) { return; } if (!tb.IsKeyboardFocusWithin) { tb.SelectAll(); e.Handled = true; tb.Focus(); } } 

对于那些对Donnelle的/ Groky的方法感兴趣的人,但是想要在最后一个字符的右边单击(但仍然在文本框内)将插入符号放在input文本的末尾,我已经想出了这个解决scheme:

  int GetRoundedCharacterIndexFromPoint(TextBox textBox, Point clickedPoint) { int position = textBox.GetCharacterIndexFromPoint(clickedPoint, true); // Check if the clicked point is actually closer to the next character // or if it exceeds the righmost character in the textbox // (in this case return increase the position by 1) Rect charLeftEdge = textBox.GetRectFromCharacterIndex(position, false); Rect charRightEdge = textBox.GetRectFromCharacterIndex(position, true); double charWidth = charRightEdge.X - charLeftEdge.X; if (clickedPoint.X + charWidth / 2 > charLeftEdge.X + charWidth) position++; return position; } void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { // Find the TextBox DependencyObject parent = e.OriginalSource as UIElement; while (parent != null && !(parent is TextBox)) parent = VisualTreeHelper.GetParent(parent); if (parent != null) { var textBox = (TextBox)parent; if (!textBox.IsKeyboardFocusWithin) { // If the text box is not yet focused, give it the focus and // stop further processing of this click event. textBox.Focus(); e.Handled = true; } else { int pos = GetRoundedCharacterIndexFromPoint(textBox, e.GetPosition(textBox)); textBox.CaretIndex = pos; } } } void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } 

GetRoundedCharacterIndexFromPoint方法是从这篇文章中获得的。

  #region TextBoxIDCard selection private bool textBoxIDCardGotFocus = false; private void TextBoxIDCard_GotFocus(object sender, RoutedEventArgs e) { this.TextBoxIDCard.SelectAll(); } private void TextBoxIDCard_LostFocus(object sender, RoutedEventArgs e) { textBoxIDCardGotFocus = false; } private void TextBoxIDCard_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if (textBoxIDCardGotFocus == false) { e.Handled = true; this.TextBoxIDCard.Focus(); textBoxIDCardGotFocus = true; } } #endregion 

我search了很多的解决scheme,我find了一些解决scheme来select但是,问题是当我们从文本框中select部分文本做右键单击和剪切/复制时,它甚至select我甚至select了部分文本。 解决这个问题就是解决scheme。 只需在键盘select事件中添加下面的代码即可。 这对我有效。

 private static void SelectContentsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TextBox) { TextBox textBox = d as TextBox; if ((e.NewValue as bool?).GetValueOrDefault(false)) { textBox.GotKeyboardFocus += OnKeyboardFocusSelectText; } else { textBox.GotKeyboardFocus -= OnKeyboardFocusSelectText; } } } private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) { if (e.KeyboardDevice.IsKeyDown(Key.Tab)) ((TextBox)sender).SelectAll(); } 

我用Nils的答案,但转换为更灵活。

 public enum SelectAllMode { /// <summary> /// On first focus, it selects all then leave off textbox and doesn't check again /// </summary> OnFirstFocusThenLeaveOff = 0, /// <summary> /// On first focus, it selects all then never selects /// </summary> OnFirstFocusThenNever = 1, /// <summary> /// Selects all on every focus /// </summary> OnEveryFocus = 2, /// <summary> /// Never selects text (WPF's default attitude) /// </summary> Never = 4, } public partial class TextBox : DependencyObject { public static readonly DependencyProperty SelectAllModeProperty = DependencyProperty.RegisterAttached( "SelectAllMode", typeof(SelectAllMode?), typeof(TextBox), new PropertyMetadata(SelectAllModePropertyChanged)); private static void SelectAllModePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is System.Windows.Controls.TextBox) { var textBox = d as System.Windows.Controls.TextBox; if (e.NewValue != null) { textBox.GotKeyboardFocus += OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown; } else { textBox.GotKeyboardFocus -= OnKeyboardFocusSelectText; textBox.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDown; } } } private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DependencyObject dependencyObject = GetParentFromVisualTree(e.OriginalSource); if (dependencyObject == null) return; var textBox = (System.Windows.Controls.TextBox)dependencyObject; if (!textBox.IsKeyboardFocusWithin) { textBox.Focus(); e.Handled = true; } } private static DependencyObject GetParentFromVisualTree(object source) { DependencyObject parent = source as UIElement; while (parent != null && !(parent is System.Windows.Controls.TextBox)) { parent = VisualTreeHelper.GetParent(parent); } return parent; } private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) { var textBox = e.OriginalSource as System.Windows.Controls.TextBox; if (textBox == null) return; var selectAllMode = GetSelectAllMode(textBox); if (selectAllMode == SelectAllMode.Never) { textBox.SelectionStart = 0; textBox.SelectionLength = 0; } else textBox.SelectAll(); if (selectAllMode == SelectAllMode.OnFirstFocusThenNever) SetSelectAllMode(textBox, SelectAllMode.Never); else if (selectAllMode == SelectAllMode.OnFirstFocusThenLeaveOff) SetSelectAllMode(textBox, null); } [AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)] [AttachedPropertyBrowsableForType(typeof(System.Windows.Controls.TextBox))] public static SelectAllMode? GetSelectAllMode(DependencyObject @object) { return (SelectAllMode)@object.GetValue(SelectAllModeProperty); } public static void SetSelectAllMode(DependencyObject @object, SelectAllMode? value) { @object.SetValue(SelectAllModeProperty, value); } } 

In XAML, you can use like one of these:

 <!-- On first focus, it selects all then leave off textbox and doesn't check again --> <TextBox attprop:TextBox.SelectAllMode="OnFirstFocusThenLeaveOff" /> <!-- On first focus, it selects all then never selects --> <TextBox attprop:TextBox.SelectAllMode="OnFirstFocusThenNever" /> <!-- Selects all on every focus --> <TextBox attprop:TextBox.SelectAllMode="OnEveryFocus" /> <!-- Never selects text (WPF's default attitude) --> <TextBox attprop:TextBox.SelectAllMode="Never" /> 

Try this extension method to add the desired behaviour to any TextBox control. I havn't tested it extensively yet, but it seems to fulfil my needs.

 public static class TextBoxExtensions { public static void SetupSelectAllOnGotFocus(this TextBox source) { source.GotFocus += SelectAll; source.PreviewMouseLeftButtonDown += SelectivelyIgnoreMouseButton; } private static void SelectAll(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e) { var textBox = (sender as TextBox); if (textBox != null) { if (!textBox.IsKeyboardFocusWithin) { e.Handled = true; textBox.Focus(); } } } } 

This seems to work well for me. It's basically a recap of some earlier posts. I just put this into my MainWindow.xaml.cs file in the constructor. I create two handlers, one for keyboard, and one for the mouse, and funnel both events into the same function, HandleGotFocusEvent , which is defined right after the constructor in the same file.

 public MainWindow() { InitializeComponent(); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent, new RoutedEventHandler(HandleGotFocusEvent), true); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotMouseCaptureEvent, new RoutedEventHandler(HandleGotFocusEvent), true); } private void HandleGotFocusEvent(object sender, RoutedEventArgs e) { if (sender is TextBox) (sender as TextBox).SelectAll(); } 

An easy way to override the mouseDown and select all after doubleclick is:

 public class DoubleClickTextBox: TextBox { public override void EndInit() { base.EndInit(); } protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e) { base.OnMouseEnter(e); this.Cursor = Cursors.Arrow; } protected override void OnMouseDown(System.Windows.Input.MouseButtonEventArgs e) { } protected override void OnMouseDoubleClick(System.Windows.Input.MouseButtonEventArgs e) { base.OnMouseDown(e); this.SelectAll(); } } 

I had same problem. In VB.Net it works easy that way:

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 

Try putting this in the constructor of whatever control is housing your textbox:

 Loaded += (sender, e) => { MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); myTextBox.SelectAll(); } 

Sergei.

After googling and testing, I've found a simple solution that worked for me.

You need to add an event handler to the "Loaded" event of your container window:

  private void yourwindow_Loaded(object sender, RoutedEventArgs e) { EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler(SelectivelyIgnoreMouseButton)); } 

Next, you have to create the handler to the referenced RoutedEventHandler in previous code:

  private void SelectivelyIgnoreMouseButton(object sender, RoutedEventArgs e) { TextBox tb = (sender as TextBox); if (tb != null) { if (!tb.IsKeyboardFocusWithin) { e.Handled = true; tb.Focus(); } } } 

Now, you can add the SelectAll() command on GotFocus event handlers to any TextBox controls separately:

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

Your text now is selected on focus!

Adapted from Dr. WPF solution, MSDN Forums

This is by far the simplest solution.

Add a global handler to the application (App.xaml.cs) and done. You are going to need only a few lines of code.

Check here: WPF TextBox SelectAll on Focus

希望能帮助到你。

I have tested all of them but only the following worked out:

  protected override void OnStartup(StartupEventArgs e) { EventManager.RegisterClassHandler(typeof(TextBox), UIElement.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyHandleMouseButton), true); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText), true); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotFocusEvent, new RoutedEventHandler(GotFocus), true); } private static void SelectivelyHandleMouseButton(object sender, MouseButtonEventArgs e) { var textbox = (sender as TextBox); if (textbox != null) { int hc = textbox.GetHashCode(); if (hc == LastHashCode) { if (e.OriginalSource.GetType().Name == "TextBoxView") { e.Handled = true; textbox.Focus(); LastHashCode = -1; } } } if (textbox != null) textbox.Focus(); } private static void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } private static int LastHashCode; private static void GotFocus(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) LastHashCode = textBox.GetHashCode(); } 

哇! After reading all the above I find myself overwhelmed and confused. I took what I thought I learned in this post and tried something completely different. To select the text in a textbox when it gets focus I use this:

 private void TextField_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = (sender as Textbox); if(tb != null) { e.Handled = true; tb.Focus(); tb.SelectAll(); } } 

Set the GotFocus property of the textbox to this method.

Running the application and clicking once in the textbox highlights everything already in the textbox.

If indeed, the objective is to select the text when the user clicks in the textbox, this seems simple and involves a whole lot less code. Just saying…