题
有没有办法隐藏或移动密码框的插入符号?
解决方案
在 .NET 3.5 SP1 或更低版本中,没有干净的方法来指定 WPF TextBox/PasswordBox 插入符号的颜色。
但是,有一种方法可以从视图中指定(或在本例中删除)该插入符号(通过 hack)。插入符号颜色是文本框/密码框背景颜色的反色。因此,您可以将背景颜色设置为“透明黑色”,这将欺骗系统使用白色插入符(不可见)。
代码(简单)如下:
<PasswordBox Background="#00000000" />
有关此问题的更多信息,请查看以下链接:
- http://cloudstore.blogspot.com/2008/09/changing-caret-colour-in-wpf.html
- http://blogs.msdn.com/llobo/archive/2007/02/08/changing-caret-color-in-textbox.aspx
请注意,在 .NET 4.0 中,插入符将是可自定义的。
希望这可以帮助!
其他提示
您可以尝试这样的事情来设置在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... or lenght of the password
SetSelection( passwordBox1, 2, 0);
// focus the control to update the selection
passwordBox1.Focus();
要获取Passwordbox的选择我使用以下代码:
private Selection GetSelection(PasswordBox pb)
{
Selection result = new Selection();
PropertyInfo infos = pb.GetType().GetProperty("Selection", BindingFlags.NonPublic | BindingFlags.Instance);
object selection = infos.GetValue(pb, null);
IEnumerable _textSegments = (IEnumerable)selection.GetType().BaseType.GetField("_textSegments", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(selection);
object first_textSegments = _textSegments.Cast<object>().FirstOrDefault();
object start = first_textSegments.GetType().GetProperty("Start", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(first_textSegments, null);
result.start = (int) start.GetType().GetProperty("Offset", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(start, null);
object end = first_textSegments.GetType().GetProperty("End", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(first_textSegments, null);
result.length = (int)start.GetType().GetProperty("Offset", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(end, null) - result.start;
return result;
}
struct Selection
{
public int start;
public int length;
}
在.NET 4.0测试,希望对你也适用。
不隶属于 StackOverflow