0

I am using a textbox for a login window. I want the textbox to display "Username" in light grey so the user knows to use that box to type in the username. Whenever the user clicks on the textbox even if it's in the middle of the word username I want the cursor to go to the first position and username will disappear when they start typing. I tried using the PreviewMouseDown event but it only works inside breakpoints but doesn't trigger at all outside it. Using the PreviewMouseUp event it works, but other caret positions can be selected before the cursor jumps to the beginning. I want it to appear like the user is unable to select any cursor position besides the first. This is the code I've tried.

private bool textboxuserfirstchange = true;

private void eventTextChanged(object sender, TextChangedEventArgs e)
{
    if (textBoxUser.Text != "Username")
    {
        if (textboxuserfirstchange)
        {
            textBoxUser.Text = textBoxUser.Text[0].ToString();
            textBoxUser.SelectionStart = 1;
            textBoxUser.Opacity = 100;
        }
    textboxuserfirstchange = false;
    } 
}

private void eventPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (textboxuserfirstchange)
    {
        textBoxUser.Focus();
        textBoxUser.Select(0, 0);     //None of these working
        textBoxUser.SelectionStart = 0;
        textBoxUser.CaretIndex = 0;
    }
}
Ryan D.
  • 57
  • 6
  • 1
    Possible duplicate of [How can I add a hint text to WPF textbox?](https://stackoverflow.com/questions/7425618/how-can-i-add-a-hint-text-to-wpf-textbox) – Jan Oct 09 '18 at 19:11
  • this might also help: https://stackoverflow.com/questions/10428230/make-default-text-to-appear-in-an-empty-textbox-without-focus-using-xaml – Jan Oct 09 '18 at 19:12

1 Answers1

0

You could for example handle the GotKeyboardFocus and PreviewTextInput event. Something like this:

private const string Watermark = "Username";
private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if (textBoxUser.Text == Watermark)
        textBoxUser.Dispatcher.BeginInvoke(new Action(() => textBoxUser.CaretIndex = 0), DispatcherPriority.Background);
}

private void textBoxUser_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (textBoxUser.Text == Watermark)
        textBoxUser.Text = string.Empty;
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • This almost works, however GotKeyboardFocus only sets the caret position the first time you click on the textbox, you can still click in the middle of username the second time. It also highlights the text sometimes. I used the event to clear the string and it works pretty well, but it removes the hint text when you click instead of when you start typing. – Ryan D. Oct 10 '18 at 15:11