WPF TextBox selectall并同时显示插入符号 [英] WPF TextBox selectall and show caret at the same time
问题描述
经过长时间的网上搜索,希望您能对我有所帮助.
after a long search on the net, I hope you can help me.
我的问题: 我想在文本框中选择完整的文本 并在最后一个字符之后显示插入符号(闪烁的光标).
My Problem: I want to select the complete text in a TextBox and will show the caret (blinking cursor) after the last character.
我总是找到有关一个问题的信息或隐藏插入符号的信息.
Always I have found information about one problem or information to hide the caret.
分开的东西没问题,但结合起来是行不通的.
The separate things are no problems but the combination of it don't work.
// 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;
因此,我在最后一个字符之后看到了插入符号,但未选择文本
So, I see the caret after the last character, but the text is not selected
myTextBox.Focus();
myTextBox.SelectAll();
myTextBox.CaretIndex = myTextBox.Text.Length;
因此,选择了文本,但未显示脱字号.
And so, the text is selected, but no caret is shown.
myTextBox.Focus();
myTextBox.CaretIndex = myTextBox.Text.Length;
myTextBox.SelectAll();
这就是问题所在:其中一个停用另一个,但我同时需要这两件事
And that's the problem: one of them deactivate the another one, but I need these two things at the same time
我使用WPF和.Net 4.0
感谢您的帮助:-)
推荐答案
问题是CaretIndex
和Selection
之间的TextBox
内部牢固的连接.
The problem is the strong internal connection in the TextBox
between CaretIndex
and the Selection
.
无论何时使用Select()
或SelectAll()
修改选择,TextBox
都会自动将CaretIndex
置于选择的开头.相反,当您手动修改CaretIndex
时,TextBox
会清除选择.如果在TextBox
中注册SelectionChanged
并将当前CaretIndex
输出到Console
,则可以使此行为可见.
Whenever you modify the selection with Select()
or SelectAll()
, the TextBox
automatically places the CaretIndex
at the beginning of the selection. In reverse, the TextBox
clears the selection when you manually modify the CaretIndex
. You can make this behavior visible, if you register for SelectionChanged
in the TextBox
and output the current CaretIndex
to Console
.
这是一个很好的理由,就像Okuma.Scott在他的评论中已经提到的那样.
This is for a good reason, as Okuma.Scott already mentioned in his comment.
因此,如果确实需要您所需的行为,则可能需要实现自己的CustomTextBox.
So if your desired behaviour is really required, you probably need to implement your own CustomTextBox.
这篇关于WPF TextBox selectall并同时显示插入符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!