简体   繁体   English

单击文本框时,在C#WPF中设置插入符号/光标位置

[英]Set the Caret/Cursor position in C# WPF when textbox clicked on

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. 我尝试使用PreviewMouseDown事件,但是它仅在断点内部起作用,而在其外部根本不触发。 Using the PreviewMouseUp event it works, but other caret positions can be selected before the cursor jumps to the beginning. 使用PreviewMouseUp事件,它可以工作,但是可以在光标跳到开头之前选择其他插入符号位置。 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;
    }
}

You could for example handle the GotKeyboardFocus and PreviewTextInput event. 例如,您可以处理GotKeyboardFocusPreviewTextInput事件。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM