Cell Editing behavior: remove PlaceCaretOnTextBox

2 posts, 0 answers
  1. Chad
    Chad avatar
    5 posts
    Member since:
    Feb 2013

    Posted 06 May 2013 Link to this post

    I'm using a TextBox in a CellEditing template in a GridView for entering data.

    The requirement is that we make sure that when someone clicks into the grid to edit, the data that is already in the text box be selected. Always. Always. The text should ALWAYS be selected when entering edit mode. We NEVER want to see the cursor until at least one new key is hit (arrow key, or other). The text should always be selected.

    So I implemented some changes to the text box as outlined here:

    http://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox

    That should in theory work for always selecting the text box.

    However, I've found that the Grid View column, when going into edit mode, always UNSELECTS the selection if you click directly on the middle of the text. In other words, it gives me a cursor and no text selection.

    Debugging into this, I've found that the culprit comes from one of the GridViewColumn classes calling "PlaceCaretOnTextBox". I want to avoid this.

    Is there a setting in the column where I can get it to stop killing the selected text when entering edit mode?


    Thanks,
    Chad Lehman
    20th Century Fox


  2. Chad
    Chad avatar
    5 posts
    Member since:
    Feb 2013

    Posted 06 May 2013 Link to this post

    The issue was solved by handling the OnSelectionChanged event
    and setting the selection again as long as the selection was not null or empty string.

    You grab the text from the control OnGetKeyboardFocus, and save it. Then compare it against SelectedText. If they are equal, you set the selection again.

    ----- In a subclassed TextBox used for in the Cell Editing template:


    protected override void OnSelectionChanged(RoutedEventArgs e)
    {
          // If we have text but it was unselected...
          if(!string.IsNullOrWhiteSpace(Text) && string.IsNullOrWhiteSpace(SelectedText))
          {
              // if we're just starting an edit, reselect the text
              if(_selected == Text)
              {
                    _selected = string.Empty;
                    e.Handled = true;
     
                    SelectAll(); // does the reselection
              }
         }
           else base.OnSelectionChanged(e);
    }
     
    protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
    {
         base.OnGotKeyboardFocus(e);
     
         _selected = Text;
    }
Back to Top