簡體   English   中英

單擊文本框時,在C#WPF中設置插入符號/光標位置

[英]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;
    }
}

例如,您可以處理GotKeyboardFocusPreviewTextInput事件。 像這樣:

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