2009-06-01 62 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測試,希望對你也有效。