文本框插入符号不会移动 WPF C#

Textbox caret isn't moving WPF C#

我试图在单击时将文本框的插入符号移动到文本框的开头但没有成功。 我尝试了多种方法,但总是得到插入符号位置不变的相同结果,我的代码中是否有任何内容可以阻止插入符号移动?我需要使用某个事件吗?

这是我的 XAML:

<TextBox Name="roomNameBox"
         Text ="Room Name"
         Margin="23,0,0,0"
         GotFocus="TextBox_GotFocus"
         LostFocus="TextBox_LostFocus"
         TextChanged="TextBox_TextChanged">

这是我的代码:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox box)
        {
            box.CaretIndex = 0;
        }
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (sender is TextBox box)
        {
            if (box.Opacity == 0.5)
            {
                box.Opacity = 1;
                box.CaretBrush = Brushes.White;
            }
        }
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if (sender is TextBox box)
        {
            if (box.Text == "")
            {
                if (box.Name == roomNameBox.Name)
                {
                    box.Text = Constants.ROOM_NAME_HINT;
                }
                else if (box.Name == timePerQuestionBox.Name)
                {
                    box.Text = Constants.TIME_PER_QUESTION_HINT;
                }
                else if (box.Name == maxPlayersBox.Name)
                {
                    box.Text = Constants.MAX_PLAYERS_HINT;
                }

                box.Opacity = 0.5;
                box.CaretBrush = new SolidColorBrush(Color.FromRgb(150, 169, 198));
            }
        }
    }

在此先感谢您的帮助

编辑: 只有当我设置断点并步进代码时代码才有效

在键盘和鼠标的 GotFocus 事件中设置 box.CaretIndex = 0;。请参阅 CaretIndex 属性 here.
将索引设置为 0 转换为将插入符号放在文本字符串内容的第一个字符(索引 0 处)之前。

一个事件在 GotFocus 之后触发,该事件将插入符号放在末尾。解决方案是实现这两个事件:

<TextBox 
Keyboard.GotKeyboardFocus="TextBox_GotKeyboardFocus" Mouse.GotMouseCapture="TextBox_GotMouseCapture"  
Text="test"></TextBox>
private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    (sender as TextBox).CaretIndex = 0;
}

private void TextBox_GotMouseCapture(object sender, MouseEventArgs e)
{
    (sender as TextBox).CaretIndex = 0;
}