【问题标题】:how to get and set current cursor position of WPF textbox如何获取和设置 WPF 文本框的当前光标位置
【发布时间】:2011-10-13 07:02:00
【问题描述】:

我想从 WPF 文本框获取当前光标位置。如果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


    【解决方案1】:

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

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

    【讨论】:

    • 这个答案与我正在寻找的 OP 标题中的答案相匹配。
    【解决方案2】:

    您只需添加一行即可将焦点设置在文本框上,否则一切正常。

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

    【讨论】:

      【解决方案3】:
      txtFunctionName.Text = _tempFuncName; 
      txtFunctionName.SelectionStart = _cursorPosition; 
      txtFunctionName.SelectionLength  = _selectionLength ; 
      

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

      【讨论】:

        【解决方案4】:

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

        txt_logArea.Select(txt_logArea.Text.Length, 0);
        txt_logArea.ScrollToCaret();
        

        【讨论】:

        • “System.Windows.Controls.TextBox”不包含“ScrollToCaret”的定义
        • 对不起!所描述的是指 System.Windows.Forms.TextBox。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-19
        • 2015-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多