【问题标题】:How can i set the caret position to a specific index in passwordbox in WPF如何将插入符号位置设置为 WPF 密码框中的特定索引
【发布时间】:2009-06-13 08:26:56
【问题描述】:

我需要在 WPF 中明确设置密码框内的光标位置。我在密码框中看不到 selectionstart 属性。

有什么帮助吗?

【问题讨论】:

    标签: c# wpf textbox passwordbox text-cursor


    【解决方案1】:

    您可以尝试这样的方法来设置 PasswordBox 中的选择:

    private void SetSelection(PasswordBox passwordBox, int start, int length) {
        passwordBox.GetType().GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(passwordBox, new object[] { start, length });
    }
    

    之后,这样调用它来设置光标位置:

    // set the cursor position to 2...
    SetSelection( passwordBox1, 2, 0);
    
    // focus the control to update the selection
    passwordBox1.Focus();
    

    【讨论】:

    • 我建议在 PreviewTextInput 中执行此操作,以确保文本输入始终位于末尾,并结合透明的 CaretBrush。
    • 非常感谢它的工作正常..你能不能更详细地回答如何从密码框中获取插入符号位置...
    【解决方案2】:

    不,PasswordBox 的 API 没有公开执行此操作的方法。

    【讨论】:

    • 谢谢肯特。有没有办法我可以使用文本框控件来实现这一点。
    • 这应该在文本框中为您完成:textBox.Select(textBox.Text.Length, 0)
    猜你喜欢
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2011-01-08
    相关资源
    最近更新 更多