[英]Set the Caret/Cursor position in C# WPF when textbox clicked on
我在登录窗口中使用文本框。 我希望文本框以浅灰色显示“用户名”,以便用户知道使用该框键入用户名。 每当用户单击文本框时,即使它位于用户名一词的中间,我也希望光标移至第一个位置,并且用户名在输入时会消失。 我尝试使用PreviewMouseDown事件,但是它仅在断点内部起作用,而在其外部根本不触发。 使用PreviewMouseUp事件,它可以工作,但是可以在光标跳到开头之前选择其他插入符号位置。 我希望它看起来像用户无法选择除第一个以外的任何光标位置。 这是我尝试过的代码。
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;
}
}
例如,您可以处理GotKeyboardFocus
和PreviewTextInput
事件。 像这样:
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.