Missing out of the box in Silverlight 3 is the ability to auto select the text in a textbox when it receives focus. Thankfully Attached Properties make it very easy to add the functionality. In this post I will create a AutoSelectText attached property, which when set to true will select all the text as when the textbox receives focus. And because of routed events, it is not required to add the property to every textbox on a page. Instead it can be added to the parent content control and all child textboxes will have to auto select behavior.
Usage
- <Grid x:Name="LayoutRoot"
- attachedProperties:AttachedProperties.AutoSelectText="true">
- <StackPanel Orientation="Vertical"
- HorizontalAlignment="Left">
- <TextBox Text="Will not auto select"
- MaxWidth="300"
- Margin="4"
- attachedProperties:AttachedProperties.PreventAutoSelectText="true" />
- <TextBox Text="Will auto select 1"
- MaxWidth="300"
- Margin="4"/>
- <TextBox Text="Will auto select 2"
- MaxWidth="300"
- Margin="4" />
- </StackPanel>
- </Grid>
Line 2: The AutoSelectText is set to true on the root level content control (Grid). That’s it. All text boxes within the Grid will participate in the auto select text functionality.
Line 8: A control can opt out by setting the PreventAutoSelectText property to false.
Listed below are some of the key code blocks. The link to the entire source code can be found at the end of the post.
Declaring the attached property
- public static readonly DependencyProperty AutoSelectTextProperty = DependencyProperty.RegisterAttached("AutoSelectText",
- typeof(Boolean),
- typeof(AttachedProperties),
- new PropertyMetadata(OnAutoSelectTextChanged));
- public static readonly DependencyProperty PreventAutoSelectTextProperty = DependencyProperty.RegisterAttached("PreventAutoSelectText",
- typeof(Boolean),
- typeof(AttachedProperties),
- null);
Line 1-2: A new boolean attached property called AutoSelectText is declared.
Line 4: The OnAutoSelectTextChanged event handler is registered, which is be invoked when the value of the property is set in the xaml.
Line 6: A new boolean attached property called PreventAutoSelectText is declared. Controls can use this property to opt out of the auto select functionality.
The dependency property changed event handler
- private static void OnAutoSelectTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- //This works because of event bubbling.
- FrameworkElement frameworkElement = d as FrameworkElement;
- if (frameworkElement != null)
- {
- if ((bool)e.NewValue)
- frameworkElement.GotFocus += OnGotFocus;
- else
- frameworkElement.GotFocus -= OnGotFocus;
- }
- }
Line 8: If the value of the AutoSelectText (accessed using e.NewValue) is true, we add the OnGotFocus event handler to the GotFocus event of the control on which the AutoSelectText property is being set (from the xaml).
Line 9: Similarly if the control does not wish to participate in auto selecting of text, we remove our event handler.
The GotFocus event handler
- private static void OnGotFocus(object sender, RoutedEventArgs e)
- {
- TextBox textBox = FocusManager.GetFocusedElement() as TextBox;
- if (textBox != null && !(bool)textBox.GetValue(PreventAutoSelectTextProperty))
- textBox.Select(0, textBox.Text.Length);
- }
Line 3: Since we are using routed events, the sender parameter will not be the textbox that currently has focus. It will the root level content control (Grid) which has the AutoSelectText attached property. The FocusManager class is used to get a reference to that control that has the focus.
Why two attached properties?
Silverlight does not provide a way to check if a control has a attached property defined in the xaml. Due to this if I replace
- if (textBox != null && !(bool)textBox.GetValue(PreventAutoSelectTextProperty))
in the OnGotFocus method with
- if (textBox != null && !(bool)textBox.GetValue(AutoSelectTextProperty))
I will always get false for the textBox.GetValue call, even if the AutoSelectText has not been defined for the textbox in xaml.
@David: Glad to be of help.
ReplyDeleteI'm trying this in a WPF project, but FocusManager.GetFocusedElement requires "DependencyObject element" as a parameter - and it won't take null as the value. Any ideas?
ReplyDeleteI just started with WPF and have the same problem as the previous poster. I have come up with a hacky solution that works for now. It’s not elegant at all so please feel free to show me a better solution. There is a caveat too. The text only gets selected if you use the keyboard and tab between text boxes. If you use the mouse to click in the box nothing happens so watch out for that.
ReplyDeleteChange the code in AttachedProperties.cs as follows:
private static DependencyObject dependencyObject;
private static void OnAutoSelectTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
dependencyObject = d;
//This works because of event bubbling.
FrameworkElement frameworkElement = d as FrameworkElement;
if (frameworkElement != null)
{
if ((bool)e.NewValue)
frameworkElement.GotFocus += OnGotFocus;
else
frameworkElement.GotFocus -= OnGotFocus;
}
}
private static void OnGotFocus(object sender, RoutedEventArgs e)
{
//Since we are using routed events, the sender parameter will not be the textbox that currently has focus.
//It will the root level content control (Grid) which has the AutoSelectText attached property.
//The FocusManager class is used to get a reference to the control that has the focus.
dependencyObject = Window.GetWindow(dependencyObject);
TextBox textBox = FocusManager.GetFocusedElement(dependencyObject) as TextBox;
if (textBox != null && !(bool)textBox.GetValue(PreventAutoSelectTextProperty))
textBox.Select(0, textBox.Text.Length);
}
very very very nice! many thanks
ReplyDeleteVery informative blog. I really enjoyed reading it and it has doubled my knowledge in it. Thanks for great work and sharing this useful information.
ReplyDeleteThanks a lot.
ReplyDeleteI'm using this on a windows phone app, it works pretty well.
Thank you so much. Excellent solution.
ReplyDeleteI really like to visit your blog,excellent information i got in your blog,thanks a lot for sharing.
ReplyDeleteIn case someone still cares: I also tried it with WPF. I simply replaced FocusManager.GetFocusedElement() with Keyboard.FocusedElement.
ReplyDeleteThis gives the correct element but the problem still is that the selection will be overwritten immediately when clicking with the mouse.
Subscribing to GotMouseCapture in addition to GotFocus fixes the mouse click problem in WPF
ReplyDelete