WPF文本框可同时选择并显示插入符号

本文关键字:显示 插入 符号 选择 文本 WPF | 更新日期: 2023-09-27 18:17:50

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

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

我总能找到一个问题的信息或者隐藏插入符号的信息。

单独的事情没有问题,但是组合在一起就不行。

// 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

谢谢你的帮助:-)

WPF文本框可同时选择并显示插入符号

问题在于CaretIndexSelection之间的TextBox内部连接较强。

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

这是一个很好的理由,因为Okuma。Scott已经在他的评论中提到了。

所以如果你想要的行为真的是必需的,你可能需要实现你自己的CustomTextBox

这对我有用:

        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();
            }
        };