如何获取和设置WPF文本框的当前光标位置

问题描述 投票:13回答:4

我想从WPF TextBox获取当前光标位置。如果TextBox包含文本abhishek并且光标在abhi之后闪烁,那么我想要那个索引,以便稍后以编程方式清除TextBox并以编程方式分配一些其他或相同的文本后我想让光标在4个字符之后闪烁。

我试过像这样得到光标位置,

_tempFuncName = txtFunctionName.Text;
_cursorPosition =  txtFunctionName.SelectionStart;
_selectionLength = txtFunctionName.SelectionLength;

并在此后的其他事件中稍稍退后一步,

txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength  = _selectionLength;

这里的下划线变量是页面级变量。

此代码无效。还有其他方法吗?

c# .net wpf
4个回答
11
投票

您可以使用文本框的caretindex属性

//You can set this property on some event
NumberOfDigits.CaretIndex = textbox.Text.Length;

5
投票

你只需要添加一行来设置文本框的焦点,否则一切正常。

txtFunctionName.Text = _tempFuncName; 
txtFunctionName.SelectionStart = _cursorPosition; 
txtFunctionName.SelectionLength  = _selectionLength ; 
txtFunctionName.Focus();

0
投票
txtFunctionName.Text = _tempFuncName; 
txtFunctionName.SelectionStart = _cursorPosition; 
txtFunctionName.SelectionLength  = _selectionLength ; 

这些陈述足以完成req的事情。我在选择编写代码的事件时犯了错误。感谢大家。


0
投票

对我来说,只设置焦点没有帮助,但滚动到插入符号。

txt_logArea.Select(txt_logArea.Text.Length, 0);
txt_logArea.ScrollToCaret();
© www.soinside.com 2019 - 2024. All rights reserved.