[英]how to get and set current cursor position of WPF textbox
I want to get the current cursor position from a WPF TextBox. 我想从WPF TextBox获取当前光标位置。 If a
TextBox
contains text abhishek
and cursor is blinking after abhi
then i want that index, so that later after clearing the TextBox
programmatically and assigning some other or same text programmatically I want to make the cursor blink just after 4 characters. 如果一个
TextBox
包含文本abhishek
并且光标在abhi
之后闪烁然后我想要那个索引,那么稍后以编程方式清除TextBox
并以编程方式分配一些其他或相同的文本后我想让光标在4个字符之后闪烁。
I have tried get cursor position like this, 我试过像这样得到光标位置,
_tempFuncName = txtFunctionName.Text;
_cursorPosition = txtFunctionName.SelectionStart;
_selectionLength = txtFunctionName.SelectionLength;
And set back at some later stage from other event like this, 并在此后的其他事件中稍稍退后一步,
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength;
Here underscore variables are page level variables. 这里的下划线变量是页面级变量。
This code is not working. 此代码无效。 Is there some other approach?
还有其他方法吗?
You can play with caretindex property of a text box 您可以使用文本框的caretindex属性
//You can set this property on some event
NumberOfDigits.CaretIndex = textbox.Text.Length;
You just need to add one line to set focus on textbox otherwise everything is working fine. 你只需要添加一行来设置文本框的焦点,否则一切正常。
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength ;
txtFunctionName.Focus();
For me, setting the focus only didn't help, but scrolling to the caret did. 对我来说,只设置焦点没有帮助,但滚动到插入符号。
txt_logArea.Select(txt_logArea.Text.Length, 0);
txt_logArea.ScrollToCaret();
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength ;
these statements are sufficient enough to do the req thing. 这些陈述足以完成req的事情。 i was making mistake in choosing event to write code.
我在选择编写代码的事件时犯了错误。 Thanks everyone.
感谢大家。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.