WPF TextBox selectall并同时显示插入符号

时间:2014-08-12 11:49:38

标签: c# wpf textbox caret selectall

经过网上长时间的搜索后,我希望你能帮助我。

我的问题: 我想在TextBox中选择完整的文本 并将在最后一个字符后显示插入符号(闪烁光标)。

我始终找到有关隐藏插入符号的一个问题或信息的信息。

单独的事情没有问题,但它的组合不起作用。

// Set the focus to the TextBox
myTextBox.Focus();

// Select the complete text, but hide the caret (blinking cursor) 
myTextBox.SelectAll();

// or
// myTextBox.Select(0, myTextBox.Text.Length);

// Set the caret after the last character, but loss the selection from the text
myTextBox.CaretIndex = myTextBox.Text.Length;

所以,我看到最后一个字符后面的插入符号,但未选中该文本

myTextBox.Focus();
myTextBox.SelectAll();
myTextBox.CaretIndex = myTextBox.Text.Length;

因此,文本被选中,但没有显示插入符号。

myTextBox.Focus();
myTextBox.CaretIndex = myTextBox.Text.Length;
myTextBox.SelectAll();

这就是问题:其中一个停用另一个,但我需要同时处理这两件事

我使用的是WPF和.Net 4.0

感谢您的帮助: - )

2 个答案:

答案 0 :(得分:0)

问题是TextBoxCaretIndex之间Selection的强大内部联系。

每当您使用Select()SelectAll()修改选择时,TextBox会自动将CaretIndex放在选择的开头。相反,TextBox会在您手动修改CaretIndex时清除选择。如果您在SelectionChanged中注册TextBox并将当前CaretIndex输出到Console,则可以使此行为可见。

正如Okuma.Scott在评论中已经提到的那样,这是有充分理由的。

因此,如果您确实需要所需的行为,则可能需要实现自己的CustomTextBox。

答案 1 :(得分:-1)

这对我有用:

        TextBox.Text = _Text;
        System.Windows.Input.Keyboard.Focus(TextBox);

        TextBox.GotFocus += (sender, e) => {
            if (_selectAll)
            {
                //I think Caret can be set here but I didn't try it
                TextBox.SelectAll();
            }
        };
相关问题