1

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

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Have a look [here](https://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox) – Krzysztof Bracha Jun 22 '17 at 12:44
  • You can use one of the solutions @KrzysztofBracha proposed in his comment, or if you only want to select text on mouse click and not on focus, use PreviewMouseUp instead on PreviewMouseDown – Arie Jun 22 '17 at 12:52
  • Possible duplicate of [How to select all text in TextBox WPF when focus?](https://stackoverflow.com/questions/53500915/how-to-select-all-text-in-textbox-wpf-when-focus) – H. de Jonge May 01 '19 at 12:12
  • Does this answer your question? [How to automatically select all text on focus in WPF TextBox?](https://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox) – StayOnTarget Jul 23 '20 at 13:34

3 Answers3

1

This is an old question, but just had a similar problem to solve.

Since I remove my string format in my text as soon as I switch to the focus, the text is changed again after reaching the focus and TextBox.SelectAll becomes ineffective.

Therefore, I extended the solution I found here with the TextChanged event.

Here is my solution maybe it helps someone

My Text Box in a List

 <GridViewColumn Header="{Binding HeaterSetpoint, Converter={StaticResource LocalizationGenericConverter}}" Width="80">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox x:Name="Setpoint" IsEnabled="{Binding SetpointEnable}" Width="50" TextAlignment="Right" 
                                     ToolTip="{Binding SetpointToolTip, Converter={StaticResource LocalizationGenericConverter}}" 
                                     behaviors:TextBoxBehavior.SelectAllTextOnFocus="True"
                                     Focusable="True">
                                <b:Interaction.Behaviors>
                                    <behaviors:TextBoxKeyDownBehavior />
                                </b:Interaction.Behaviors>
                                <TextBox.Style>
                                    <Style TargetType="{x:Type TextBox}">
                                        <Style.Triggers>
                                            <Trigger Property="IsFocused" Value="true">
                                                <Setter Property="Text" Value="{Binding Setpoint, UpdateSourceTrigger=LostFocus, Mode=TwoWay}" />
                                            </Trigger>
                                        </Style.Triggers>
                                        <Setter Property="Text" Value="{Binding Setpoint, StringFormat={}0.## C°, UpdateSourceTrigger=LostFocus}" />
                                    </Style>
                                </TextBox.Style>
                            </TextBox>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>

My Text Box Behavior

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.TextChanged -= SelectAllAfterChange;
            textBox.PreviewMouseDown -= IgnoreMouseButton;
        }
    }

    private static void SelectAll(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox == null) return;
        textBox.Focus();
        textBox.TextChanged += SelectAllAfterChange;
    }

    private static void SelectAllAfterChange(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox == null) return;
        textBox.TextChanged -= SelectAllAfterChange;
        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();
    }
}
klementuel
  • 43
  • 4
0

The problem is how the control is focused after the event is fired. You need to write e.Handled = true;, which prevents focus from bubbling.

private void XValue_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
     TextBox textbox = (TextBox)sender;
     textbox.Focus();
     textbox.SelectAll();
     e.Handled = true;
}
Krythic
  • 4,184
  • 5
  • 26
  • 67
  • 1
    Can someone elaborate as to why this was downvoted? This is the actual solution to the question. – Krythic Oct 28 '19 at 19:42
  • 1
    I had to add ((TextBox)sender).Focus(); before SelectAll to make this work. – Frederik May 07 '20 at 09:39
  • @Frederik Interesting. – Krythic May 09 '20 at 01:29
  • 1
    @Frederik Strangely enough, a year later, I had this same problem again, and my initial answer no longer worked. Your suggestion of adding Focus before Select all fixed it. I have no idea why this behaved differently in another project. I updated the answer to reflect your suggestion. – Krythic Jul 25 '21 at 05:56
-1

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    You actually don't need any of this. Just make sure you call e.Handled = true; after SelectAll. – Krythic Oct 26 '19 at 17:11