WPF TextBox selectall并同时显示插入符号 [英] WPF TextBox selectall and show caret at the same time

查看:177
本文介绍了WPF TextBox selectall并同时显示插入符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过长时间的网上搜索,希望您能对我有所帮助.

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

感谢您的帮助:-)

推荐答案

问题是CaretIndexSelection之间的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆