0

I have a TextBox I use to display a file path and I'd like the caret and focus to always be at the end of path rather than the front. I've accomplished this with the help of this question: Setting cursor at end of textbox. It works!

InitializeComponent();

FilePathTextBox.Focus();
FilePathTextBox.Select(FilePathTextBox.Text.Length, 0);

However, I added a browse button to the user could select their own save location, and when the folder select dialog closes, the caret returns to the front of the file path again. I tried using the click event on the browse button to call the above code but it does not work.

private void BrowseBtnClick(object sender, RoutedEventArgs e)
{
   BackupFileLocationTextBox.Focus();
   BackupFileLocationTextBox.Select(BackupFileLocationTextBox.Text.Length, 0);
   BackupFileLocationTextBox.CaretIndex = BackupFileLocationTextBox.Text.Length;
}

Any idea how to do this?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
liquidair
  • 177
  • 2
  • 11

1 Answers1

1

Instead of setting the selected text when the window opens, set it whenever the TextBox receives focus:

<TextBox Name="BackupFileLocationTextBox" GotKeyboardFocus="BackupFileLocationTextBox_GotKeyboardFocus"/>
private void BackupFileLocationTextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    BackupFileLocationTextBox.CaretIndex = BackupFileLocationTextBox.Text.Length;
}

You should keep the line FilePathTextBox.Focus(); where it is.

Note that if the user sets focus by clicking somewhere in the TextBox, the caret will move to the position they've clicked.

Keith Stein
  • 6,235
  • 4
  • 17
  • 36
  • At first glance, I thought for sure this wasn't going to work, but it does exactly what I wanted. Thank you! For learning purposes, how/why does this work? Like, why does the textbox get "KeyboardFocus" when the folder select dialog close? – liquidair May 01 '20 at 02:25
  • @liquidair You're welcome, please [accept my answer](https://stackoverflow.com/help/someone-answers) then :) – Keith Stein May 01 '20 at 02:30
  • 1
    @liquidair To answer your question, though, the `TextBox` loses keyboard focus when the `Button` is clicked. I believe it only gets it back after being manually re-focused, at which point the code provided sets the caret position. – Keith Stein May 01 '20 at 02:32
  • Interesting stuff. WPF is just insane in it's vastness. Thank you again! – liquidair May 01 '20 at 02:47