When a new window is opened, I want to focus a specific textbox and select the whole text in it. I tried it on base of this tutorial: https://blogs.msdn.microsoft.com/argumentnullexceptionblogpost/2013/04/12/a-simple-selectall-behavior-for-textboxes/
For focussing the element I use this in my Grid:
<Grid d:DataContext="{StaticResource DesignTimeLayerViewModel1}" FocusManager.FocusedElement="{Binding ElementName=LayerNameInput}">
And tried it with an interaction behavior:
<TextBox x:Name="LayerNameInput"
Text="{Binding MapLayerName, UpdateSourceTrigger=PropertyChanged}"
VerticalContentAlignment="Center"
Width="240">
<i:Interaction.Behaviors>
<behaviors:SelectAllTextBoxBehavior></behaviors:SelectAllTextBoxBehavior>
</i:Interaction.Behaviors>
</TextBox>
Behavior Code:
public class SelectAllTextBoxBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.GotFocus += this.OnTextBoxGotFocus;
}
protected override void OnDetaching()
{
this.AssociatedObject.GotFocus -= this.OnTextBoxGotFocus;
base.OnDetaching();
}
private void OnTextBoxGotFocus(object sender, RoutedEventArgs e)
{
this.AssociatedObject.SelectAll();
}
}
The Problem is the binding. When the window is created, the behavior fires correct, but actually there is no text in the TextBox. Then the TextBox is initialized and set the text to the value of the binded variable and the selection is lost. If I refocus the TextBox by use multiple times Tab, it works fine.
How is it possible to focus a TextBox and select its whole text on window creation? Without a massive amount of code behind it?
Thanks in advance!
I fixed the problem with a workaround. When the intial text of the TextBox is set during window startup, the OnTextBoxTextChanged event is fired. I just catch it, select the text and than deatach the event.
The benefit of this compared to your answer Dark Templar is, that when I focus the TextBox again e.g. with tab, the whole text is selected again.
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.GotFocus += OnTextBoxGotFocus;
AssociatedObject.TextChanged += OnTextBoxTextChanged;
}
protected override void OnDetaching()
{
AssociatedObject.GotFocus -= OnTextBoxGotFocus;
AssociatedObject.TextChanged -= OnTextBoxTextChanged;
base.OnDetaching();
}
private void OnTextBoxGotFocus(object sender, RoutedEventArgs e)
{
AssociatedObject.SelectAll();
}
private void OnTextBoxTextChanged(object sender, RoutedEventArgs e)
{
AssociatedObject.SelectAll();
AssociatedObject.TextChanged -= OnTextBoxTextChanged;
}