0

Im having troubles with Selecting All content inside of a TextBox.

Ussually by pressing enter I'm jumping from one textbox to another, because there are like 6-7 TextBoxes below each other in my Grid, and by pressing enter I need to jump from one to another,

 private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
  {

     if (e.Key == Key.Enter)
     {

        UIElement element = e.Source as UIElement;
        element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

        //TextBox tb = (sender as TextBox);
        //if (tb != null)
        //{
        //    tb.SelectAll();
        //}

     }
  }

And while I'm on some of them when I press Enter I'm doing some calculation like this:

private void txt2_PreviewKeyDown(object sender, KeyEventArgs e)
{
   if (e.Key == Key.Return)
        {
            try
            {
                CalculateSomethingFromOtherTextBoxes();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
}

My Question is next: When I jump from each other and when I finish calculation (enter is pressed), the next TextBox I will jump to I would like SELECTALL of TextBox's content when I jumped on it. In case I want to edit some value or whatever, and it is confusing sometimes content insidee is selected and sometimes it is not.

I tried setting GotFocus event on each of TextBoxes and It looks like this:

private void txt3_GotFocus(object sender, RoutedEventArgs e)
{
     txt3.SelectAll();
}

But unfortunately somehow this is sometimes working sometimes it is not, I mean all of content is selected sometimes and sometimes it is not..

Thanks guys Cheers

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102

2 Answers2

1

Try to handle the GotKeyboardFocus event instead of the GotFocus event. This should work:

private void txt3_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    txt3.SelectAll();
}
mm8
  • 163,881
  • 10
  • 57
  • 88
0

There is no property that you can set to select all of the Text in a TextBlock or TextBox. Selecting all text must be accomplished using the TextBoxBase.SelectAll Method. What you could do in a Style is to set an event handler for the GotFocus event, where the handler code would call SelectAll, but your handler would of course need to be in code and not XAML.

One other possibility would be for you to create an Attached Property that would select the text whenever the TextBox gets focus, but again it's not possible to do this in XAML.

  • And what do you think about adding finally block in my private void txt2_PreviewKeyDown and there I might manually do like this: txt3.SelectAll(); //Select next control – Roxy'Pro Apr 04 '17 at 12:42
  • Its okay if you're not going to move the textboxes and they keep the same order as now. Else you'll have to re-write your code at a later state. – Тодор Иванов Apr 04 '17 at 12:48