Search code examples
c#wpfeventstextbox

Select all text inside TextBox WPF


I don't know why my code doesn't work. I want, when an textBox is clicked in, select all text inside to edit it at whole.

My code :

private void XValue_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    ((TextBox)sender).SelectAll();
}

XAML code:

<TextBox x:Name="XValue" Text="{Binding XInitValue, StringFormat={}{0:#,0.0000}}" Width="80" VerticalAlignment="Center" PreviewMouseDown="XValue_PreviewMouseDown" ></TextBox>

The event happens, but the text is not selected


Solution

  • You could handle the GotKeyboardFocus event and use the dispatcher:

    private void XValue_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        var textBox = ((TextBox)sender);
        textBox.Dispatcher.BeginInvoke(new Action(() =>
        {
            textBox.SelectAll();
        }));
    }
    

    Or the PreviewMouseDown event. The key is to use the dispatcher.