如何在WPF的密码框中将插入符号位置设置为特定索引?

7
我需要在WPF中显式设置密码框内的光标位置。我无法在密码框中看到selectionstart属性。有什么帮助吗?
2个回答

21
您可以尝试像这样设置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。 - Rubarb
非常感谢,它运行良好。您是否可以进一步完善您的答案,说明如何从密码框中获取插入符位置? - Rakibul

1
不,PasswordBox的API没有提供这样做的方法。

谢谢Kent。有没有办法可以使用文本框控件来实现这个? - deepak
这应该可以在文本框中为您完成:textBox.Select(textBox.Text.Length, 0) - Marwan مروان

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接