If I call SelectAll
from a GotFocus
event handler, it doesn't work with the mouse - the selection disappears as soon as mouse is released.
EDIT: People are liking Donnelle's answer, I'll try to explain why I did not like it as much as the accepted answer.
This question is related to
.net
wpf
silverlight
textbox
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();
}
}
#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
I've found none of the answers presented here mimic a standard Windows textbox. For instance, try to click in the white space between the last character of the textbox and the right side of the textbox. Most of the solutions here will always select the whole content, which makes it very difficult to append text to a textbox.
The answer that I present here behaves better in this respect. It is a behavior (so it requires the System.Windows.Interactivity assembly from the Blend SDK). It could be rewritten using attached properties as well.
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;
}
}
This is based on code I've found here.
WOW! 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...
In App.xaml file:
<Application.Resources>
<Style TargetType="TextBox">
<EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/>
</Style>
</Application.Resources>
In App.xaml.cs file:
private void TextBox_GotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e)
{
((TextBox)sender).SelectAll();
}
With this code you reach all TextBox
in your application.
I searched a lot for the solution, I found couple of solutions to selectall But, the issue is when we do right click and do cut/copy after selecting part of text from text box, it selects all even I selected part of text. To fix this here is the solution. Just add the below code in the keyboard select event. This worked for me.
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();
}
Here is the C# version of the answer posted by @Nasenbaer
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);
}
whereas MyTextBox_GotFocus
is the event handler assigned to the GotFocus
event of MyTextBox
.
If there's an event that deselects text during the OnFocus
mouse up, I usually just delay the select all.
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (TextBox.Text != null)
{
_ = Task.Run(() =>
{
Dispatcher.Invoke(
async () => {
await Task.Delay(100);
TextBox.SelectAll();
}
);
});
}
}
Taken from here:
Register global event handler in App.xaml.cs file:
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(TextBox),TextBox.GotFocusEvent,
new RoutedEventHandler(TextBox_GotFocus));
base.OnStartup(e);
}
Then the handler is as simple as:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
(sender as TextBox).SelectAll();
}
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();
}
}
}
}
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
Donnelle's answer works the best, but having to derive a new class to use it is a pain.
Instead of doing that I register handlers the handlers in App.xaml.cs for all TextBoxes in the application. This allows me to use a Donnelle's answer with standard TextBox control.
Add the following methods to your 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();
}
}
I have a slightly simplified answer for this (with just the PreviewMouseLeftButtonDown
event) which seems to mimic the usual functionality of a browser:
In XAML you have a TextBox
say:
<TextBox Text="http://www.blabla.com" BorderThickness="2" BorderBrush="Green" VerticalAlignment="Center" Height="25"
PreviewMouseLeftButtonDown="SelectAll" />
In codebehind:
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();
}
}
I realize this is very old, but here is my solution which is based on the expressions/microsoft interactivity and interactions name spaces.
First, I followed the instructions at this link to place interactivity triggers into a style.
Then it comes down to this
<Style x:Key="baseTextBox" TargetType="TextBox">
<Setter Property="gint:InteractivityItems.Template">
<Setter.Value>
<gint:InteractivityTemplate>
<gint:InteractivityItems>
<gint:InteractivityItems.Triggers>
<i:EventTrigger EventName="GotKeyboardFocus">
<ei:CallMethodAction MethodName="SelectAll"/>
</i:EventTrigger>
<i:EventTrigger EventName="PreviewMouseLeftButtonDown">
<ei:CallMethodAction MethodName="TextBox_PreviewMouseLeftButtonDown"
TargetObject="{Binding ElementName=HostElementName}"/>
</i:EventTrigger>
</gint:InteractivityItems.Triggers>
</gint:InteractivityItems>
</gint:InteractivityTemplate>
</Setter.Value>
</Setter>
</Style>
and this
public void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
TextBox tb = e.Source as TextBox;
if((tb != null) && (tb.IsKeyboardFocusWithin == false))
{
tb.Focus();
e.Handled = true;
}
}
In my case, I have a user control where the text boxes are that has a code-behind. The code-behind has the handler function. I gave my user control a name in XAML, and I am using that name for the element. This is working perfectly for me. Simply apply the style to any TextBox
where you would like to have all the text selected when you click in the TextBox
.
The first CallMethodAction
calls the text box's SelectAll
method when the GotKeyboardFocus
event on the TextBox
fires.
I hope this helps.
I have chosen part of Donnelle's answer (skipped the double-click) for I think this a more natural. However, like gcores I dislike the need to create a derived class. But I also don't like gcores OnStartup
method. And I need this on a "generally but not always" basis.
I have Implemented this as an attached DependencyProperty
so I can set local:SelectTextOnFocus.Active = "True"
in xaml. I find this way the most pleasing.
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);
}
}
For my "general but not always" feature I set this Attache Property to True
in a (global) TextBox
Style
. This way "selecting the Text" is always "on", but I can disable it on a per-textbox-basis.
Here is an attempt to solve some of the problems with other solutions:
The code I wrote is configurable. You can choose on what actions the select all behavior should occur by setting three readonly fields: SelectOnKeybourdFocus
, SelectOnMouseLeftClick
, SelectOnMouseRightClick
.
The downside of this solution is that it's more complex and static state is stored. Its seems like an ugly struggle with the defaults behavior of the TextBox
control. Still, it works and all the code is hidden in the Attached Property container class.
public static class TextBoxExtensions
{
// Configuration fields to choose on what actions the select all behavior should occur.
static readonly bool SelectOnKeybourdFocus = true;
static readonly bool SelectOnMouseLeftClick = true;
static readonly bool SelectOnMouseRightClick = true;
// Remembers a right click context menu that is opened
static ContextMenu ContextMenu = null;
// Remembers if the first action on the TextBox is mouse down
static bool FirstActionIsMouseDown = false;
public static readonly DependencyProperty SelectOnFocusProperty =
DependencyProperty.RegisterAttached("SelectOnFocus", typeof(bool), typeof(TextBoxExtensions), new PropertyMetadata(false, new PropertyChangedCallback(OnSelectOnFocusChanged)));
[AttachedPropertyBrowsableForChildren(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
public static bool GetSelectOnFocus(DependencyObject obj)
{
return (bool)obj.GetValue(SelectOnFocusProperty);
}
public static void SetSelectOnFocus(DependencyObject obj, bool value)
{
obj.SetValue(SelectOnFocusProperty, value);
}
private static void OnSelectOnFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is TextBox textBox)) return;
if (GetSelectOnFocus(textBox))
{
// Register events
textBox.PreviewMouseDown += TextBox_PreviewMouseDown;
textBox.PreviewMouseUp += TextBox_PreviewMouseUp;
textBox.GotKeyboardFocus += TextBox_GotKeyboardFocus;
textBox.LostKeyboardFocus += TextBox_LostKeyboardFocus;
}
else
{
// Unregister events
textBox.PreviewMouseDown -= TextBox_PreviewMouseDown;
textBox.PreviewMouseUp -= TextBox_PreviewMouseUp;
textBox.GotKeyboardFocus -= TextBox_GotKeyboardFocus;
textBox.LostKeyboardFocus -= TextBox_LostKeyboardFocus;
}
}
private static void TextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (!(sender is TextBox textBox)) return;
// If mouse clicked and focus was not in text box, remember this is the first click.
// This will enable to prevent select all when the text box gets the keyboard focus
// right after the mouse down event.
if (!textBox.IsKeyboardFocusWithin)
{
FirstActionIsMouseDown = true;
}
}
private static void TextBox_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
if (!(sender is TextBox textBox)) return;
// Select all only if:
// 1) SelectOnMouseLeftClick/SelectOnMouseRightClick is true and left/right button was clicked
// 3) This is the first click
// 4) No text is selected
if (((SelectOnMouseLeftClick && e.ChangedButton == MouseButton.Left) ||
(SelectOnMouseRightClick && e.ChangedButton == MouseButton.Right)) &&
FirstActionIsMouseDown &&
string.IsNullOrEmpty(textBox.SelectedText))
{
textBox.SelectAll();
}
// It is not the first click
FirstActionIsMouseDown = false;
}
private static void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (!(sender is TextBox textBox)) return;
// Select all only if:
// 1) SelectOnKeybourdFocus is true
// 2) Focus was not previously out of the application (e.OldFocus != null)
// 3) The mouse was pressed down for the first after on the text box
// 4) Focus was not previously in the context menu
if (SelectOnKeybourdFocus &&
e.OldFocus != null &&
!FirstActionIsMouseDown &&
!IsObjectInObjectTree(e.OldFocus as DependencyObject, ContextMenu))
{
textBox.SelectAll();
}
// Forget ContextMenu
ContextMenu = null;
}
private static void TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (!(sender is TextBox textBox)) return;
// Remember ContextMenu (if opened)
ContextMenu = e.NewFocus as ContextMenu;
// Forget selection when focus is lost if:
// 1) Focus is still in the application
// 2) The context menu was not opened
if (e.NewFocus != null
&& ContextMenu == null)
{
textBox.SelectionLength = 0;
}
}
// Helper function to look if a DependencyObject is contained in the visual tree of another object
private static bool IsObjectInObjectTree(DependencyObject searchInObject, DependencyObject compireToObject)
{
while (searchInObject != null && searchInObject != compireToObject)
{
searchInObject = VisualTreeHelper.GetParent(searchInObject);
}
return searchInObject != null;
}
}
To attache the Attached Property to a TextBox
, all you need to do is add the xml namespace (xmlns
) of the Attached Property and then use it like this:
<TextBox attachedprop:TextBoxExtensions.SelectOnFocus="True"/>
Some notes about this solution:
TextBox
remembers its selection after it loses focus. I actually have overridden this behavior.TextBox
(FirstActionIsMouseDown
static field).ContextMenu
static field).The only side effect I found is when SelectOnMouseRightClick
is true. Sometimes the right-click context menu flickers when its opened and right-clicking on a blank are in the TextBox
does not do "select all".
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.
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(TextBox),
TextBox.GotFocusEvent,
new RoutedEventHandler(TextBox_GotFocus));
base.OnStartup(e);
}
So use the EventManager class to register a global event handler against a type (TextBox). The actual handler is dead simple:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
(sender as TextBox).SelectAll();
}
Check here: WPF TextBox SelectAll on Focus
Hope it helps.
For those interested in Donnelle's/Groky's approach, but want a click to the right of the last character (but still within the TextBox
) to place the caret at the end of the entered text, I've come up with this solution:
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();
}
The GetRoundedCharacterIndexFromPoint
method was taken from this post.
Try putting this in the constructor of whatever control is housing your textbox:
Loaded += (sender, e) =>
{
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
myTextBox.SelectAll();
}
I think this works well:
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);
}
If you would like to implement it as an extension method:
public static void SelectAllText(this System.Windows.Controls.TextBox tb)
{
tb.Dispatcher.BeginInvoke(
new Action(delegate
{
tb.SelectAll();
}), System.Windows.Threading.DispatcherPriority.Input);
}
And in your GotFocus
event:
private void ValueText_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = (TextBox)e.OriginalSource;
tb.SelectAllText();
}
I discovered the solution above because several months ago I was looking for a way to set focus to a given UIElement
. I discovered the the code below somewhere (credit is hereby given) and it works well. I post it even though it is not directly related to the OP's question because it demonstrates the same pattern of using Dispatcher
to work with a 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);
}
I had same problem. In VB.Net it works easy that way:
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# (thanks to 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);
}
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();
}
The simplist and perfect solution, is to use a timer to select all text 20ms after textbox got focus:
Dim WithEvents Timer As New DispatcherTimer()
Set the interval:
Timer.Interval = TimeSpan.FromMilliseconds(20)
respond to events (I am inheriting the TextBox control here, so I am overriding its events:
Protected Overrides Sub OnGotFocus(e As RoutedEventArgs)
Timer.Start()
MyBase.OnGotFocus(e)
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
Timer.Stop()
Me.SelectAll()
End Sub
And that is all!
Here are the Blend behaviors implementing the answer solution for your convenience:
One for attaching to a single TextBox:
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;
}
}
}
And one for attaching to the root of a container containing multiple TextBox'es:
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();
}
}
I solved this problem using an Attached Behavior rather than an Expression Behavior as in Sergey's answer. This means I don't need a dependency on System.Windows.Interactivity
in the Blend SDK:
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.IsReadOnly && textBox.IsKeyboardFocusWithin)) return;
e.Handled = true;
textBox.Focus();
}
}
You can then use it in your XAML like this:
<TextBox Text="Some Text" behaviors:TextBoxBehavior.SelectAllTextOnFocus="True"/>
I blogged about it here.
This simple implementation works perfectly for me:
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;
}
}
To apply it to all TextBox
's, put the following code after InitializeComponent();
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseDownEvent, new MouseButtonEventHandler(TextBox_PreviewMouseDown));
We have it so the first click selects all, and another click goes to cursor (our application is designed for use on tablets with pens).
You might find it useful.
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();
}
}
Here's a very good very simple solution on MSDN:
<TextBox
MouseDoubleClick="SelectAddress"
GotKeyboardFocus="SelectAddress"
PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" />
Here's the code behind:
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();
}
}
}
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();
}
I have used Nils' answer but converted to more flexible.
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" />
Source: Stackoverflow.com