WPF PasswordBox Caret

让人想犯罪 __ 提交于 2019-12-05 16:52:16

In .NET 3.5 SP1 or previous, there is no clean way to specify the color of a WPF TextBox/PasswordBox caret.

However, there is a way to specify (or in this case remove) that caret from view (via a hack). The caret color is the inverse color of the TextBox/PasswordBox's background color. THus, you can make the background color "transparent black", which will fool the system into using a white caret (which is not visible).

The code is (simply) as follows:

<PasswordBox Background="#00000000" />

For further information on this issue, please check out the following links:

Note that in .NET 4.0 the Caret will be customizable.

Hope this helps!

sameer

You can try something like this to set the selection in the PasswordBox:

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

After that, call it like this to set the cursor position:

// set the cursor position to 2... or lenght of the password
SetSelection( passwordBox1, 2, 0); 

// focus the control to update the selection 
passwordBox1.Focus(); 

To Get the selection of Passwordbox i use this code:

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;
}   

Tested at .net 4.0, hope that works for you too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!