2009-06-01 63 views
4

有没有办法隐藏或移动PasswordBox的脱字符?WPF PasswordBox Caret

+0

你可能会详细阐述一下吗? – Joey 2009-06-01 17:24:17

回答

5

在.NET 3.5 SP1或之前版本中,没有干净的方式来指定WPF TextBox/PasswordBox插入符的颜色。

但是,有一种方法可以指定(或者在这种情况下删除)从视图(通过黑客)的脱字符。脱字符颜色是TextBox/PasswordBox背景颜色的反色。因此,您可以将背景色设置为“透明黑色”,这会欺骗系统使用白色字符(不可见)。

的代码是(简单)如下:

<PasswordBox Background="#00000000" /> 

有关此问题的更多信息,请查看以下链接:

请注意,在.NET 4.0中,插入符号将定制能够。

希望这会有所帮助!

+0

我知道这是一个古老的线程,但有人知道任何关于4.0中的“可定制克拉”吗?我找不到它 – DefenestrationDay 2010-12-10 01:47:03

2

你可以尝试这样的事情来设置在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(); 
1

要获取的选择密码箱我使用这个代码:

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测试,希望对你也有效。